Use jQuery to place tags around the content of existing <li> elements

Using jquery, I have been able to successfully create a list by using the following code: $(list).append(item); (where list is the list reference and item consists of the $('<li>') elements being added).

var item = $('<li>')
$(item).append('Some Data').append('some more data');
$(list).append(item);

The list is generated in the format below, which has been working well:

<ul>
    <li>Some data, and some more Data from the 'list' var</li>
    <li>Some data, and some more Data from the 'list' var</li>
    <li>Some data, and some more Data from the 'list' var</li>
    <li>Some data, and some more Data from the 'list' var</li>
</ul>

Now, I want to enhance the appearance of this list with some css. I am looking to wrap different tags around elements within the list but I am having trouble with the syntax.

My desired outcome is as follows:

<ul>
    <li><div>Some data and <h3>some more Data from the ‘list’ var</h3></div></li>
    <li><div>Some data and <h3>some more Data from the ‘list’ var</h3></div></li>
    <li><div>Some data and <h3>some more Data from the ‘list’ var</h3></div></li>
    <li><div>Some data and <h3>some more Data from the ‘list’ var</h3></div></li>
    <li><div>Some data and <h3>some more Data from the ‘list’ var</h3></div></li>
</ul>

I have attempted to manually add the tags using methods like + “<div>” and + “</div>” but it seems to close the tags simultaneously (resulting in <div></div>). I have also tried using .append(“<div>”) at specific points in the string with similar outcomes. Additionally, using .wrap() caused the text to disappear completely, indicating a syntax error.

Could someone provide guidance on the best approach to achieve my desired result?

Answer №1

You have the ability to attach additional content to your new item, including other components that you generate using jQuery.

Prior to inserting your input into the current list, you can enclose the added components within a separate tag:

var list = document.querySelector('ul');

    $('<li>')
      .append('some data') // insert text
      .append($('<h3>', { text: 'some more data' })) // insert h3 with text
      .wrapInner('<div>') // enclose everything in div
      .appendTo(list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>

Answer №2

Wrap the inner content using .wrapInner()

$('ul li').wrapInner('<div />');

$('ul li div').html(function(i, html){
    return html.substring(0, 15) + '<h3>' + html.substring(15) + '</h3>'
});

Check out the demonstration: Fiddle

Keep in mind: Specify the content to be wrapped with h3

Answer №3

To properly format the content of the LI element, you can use jQuery to wrap the contents, including raw text nodes:

$('li').contents().wrap("<div><h3/></div>");

JSFiddle example: http://jsfiddle.net/TrueBlueAussie/a447v8d9/

Alternatively, you can use the shorter method suggested by @Arun P Johny using wrapInner

$('li').wrapInner('<div><h3/></div>');

JSFiddle example: http://jsfiddle.net/TrueBlueAussie/a447v8d9/5/

When wrapping content in nested elements, the elements will be placed inside the deepest element. For example, see http://jsfiddle.net/TrueBlueAussie/a447v8d9/4/

Additionally, only the first root level element in the wrapper is utilized. For more details, refer to http://jsfiddle.net/TrueBlueAussie/a447v8d9/3/

Update:

If you only want to wrap certain parts of the text within the H3, consider modifying the html() as suggested by @Arun P Johny.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A single snippet of JavaScript blocking the loading of another script

I've encountered an issue where the code seems to be conflicting with itself. The top part works fine, but the bottom part doesn't. However, when I remove the top portion, everything works as intended! You can see a working example of both compo ...

Optimizing performance with ng-if for 500 watchers

When repeating data with ng repeat, I encountered an issue where some of the data.image (src) values were null and I did not want them to be included in the repeat process. To solve this issue, I implemented a simple ng-if statement. <div ng-repeat="d ...

The returned data from a Apollo Client useMutation call is consistently undefined

Currently, I have a code snippet that executes a mutation to update a post to "published." The mutation functions correctly and updates the data as intended. However, I am facing an issue where the data property remains undefined in the useMutation hook. S ...

"Exploring Mocha and Chai: Tips for Generating a Comprehensive List of Errors in Test Cases

I am currently working on a unit test to validate a list of elements. Example: arr = [ { element : "aaa", validation : false }, { element: "bbbb", validation: true }, { element: "ccc", validation: false } While running my unit test, I encountered ...

Select only eBook files using this HTML form: {file-type}

I am looking to implement a form that includes an option to upload files by selecting "choose file". However, I want to restrict the displayed files to only show .epub and .mobi files when the user opens the selection pop-up box on their operating system. ...

Updating the placeholder text of a textarea using a conditional statement in PHP

I currently have a textarea within a form that is being outputted: <textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea> ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

Looking for advice on manipulating arrays in a photo viewer using jQuery and JSON?

I have developed a photo viewer from scratch which is functioning well, but with a few concerns. The code structure is as follows: Initially, I retrieve the ID of the current album and display all the images associated with that album. Upon clicking on a ...

Avoiding the use of a particular URL when using this.router.navigate() in AngularJs

In my angularJS registration form, I am using a bootstrap template for the design. The URL path to access the form page is http://localhost:4200/signup <form method="post" (submit)='register(username.value,email.value,password.value)'> ...

Creating a customized display on a webpage using XML and XSL to generate unique

Looking to utilize my xml file for generating various xsl pages. <movies> <movie> <name>Shark tank</name> <movie> <movie> <name>Tank Shark</name> <movie> ...

Adjust the font size to fit within the container

My webpage features a bootstrap 4 container with three columns that adjust on screen sizes above the md breakpoint (col-md-4). Each column contains an img with the class img-fluid, and when hovered over, text description appears. I want this hover text to ...

Is there a way to automatically send users to a different PHP file once they click "submit"?

I need to redirect to a different php file named index2.php. The username and password values are already set as follows: Username=sid, Password=yeaoklogin. When the user clicks on the Login button, they should be redirected to a page called index2.php. ...

Embedding the @media tag directly into a class for simplification and to eliminate redundancy

For the complete css/html code sample, please visit: https://jsfiddle.net/menelaosbgr/jbnsd9hc/1/ Here are two specific definitions I am working with: /* Dropdown Content (Hidden by Default) */ .dropdown-content { display: none; position: absolut ...

The functionality of ngSubmit and ngDisabled seems to be malfunctioning, although ngModel is successfully linked to the

Despite following the usual process of creating a form in AngularJS, the ngSubmit function is not working as expected and the ngDisabled feature is failing to disable the button when the fields are empty. I even tried isolating the section in a new project ...

Tips for effectively adjusting lighting in a customized shader material

Presenting a demonstration showcasing the use of a height map in three.js coupled with custom shader(s). Everything appears to be functioning smoothly now. The working demo can be found on this link. Below are the shader scripts: <script id="vertexShad ...

How can I incorporate random variables and functions into an if-else function when using Jquery to make #divId droppable?

I have most of my code working as I want it to, except for some basic CSS adjustments that need to be made. In a specific part of my code where I am using $("#divId").droppable({over: function(), I want to add 2 other functions and have one of them execute ...

Error: authentication failed during npm installation due to an incorrect URL

After executing npm install @types/js-cookie@^2.2.0, an error occurred: npm install @types/js-cookie@^2.2.0 npm ERR! code E401 npm ERR! Unable to authenticate, need: Basic realm="https://pkgsprodsu3weu.app.pkgs.visualstudio.com/" npm ERR! A com ...

"Unlocking the Power of jQuery and jTemplates: A Guide to Extracting Accurate Values

I am facing challenges in configuring the correct format for jTemplates and could really use some assistance. My setup includes an ASP.NET page with a WebMethod that returns data to jQuery. The data is then supposed to be processed by jTemplates, but I am ...

What is the best way to showcase the properties of multiple files with the help of

I have been attempting to utilize jQuery to exhibit the specifics of several uploaded files. Below is my code: <!DOCTYPE html> <html> <head> <title>jQuery Multi File Upload</title> </head> <body> <f ...

Creating a loading mask for a section of a webpage using angularjs

How can I implement a loading mask/image for a $http request that loads data for a <select> tag on my webpage? I want the loading mask/image to only cover the specific section of the page where the data is being loaded. Here's the HTML code: & ...