Add an item to an HTML list with JavaScript/jQuery
This post will discuss how to add an item to an ordered or unordered list in HTML in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can create a new <li> element and add it to an existing <ol> or <ul> element using the .append() or the .prepend() method.
The .append() method inserts the specified content at the end of the matched elements, while the .prepend() method inserts it at the beginning.
jQuery
|
1 2 3 |
$(document).ready(function() { $("ul").append($("<li>").html("Scooter")); }); |
HTML
|
1 2 3 4 5 |
<ul> <li>Car</li> <li>Bike</li> <li>Cycle</li> </ul> |
The code can be shortened to:
jQuery
|
1 2 3 |
$(document).ready(function() { $("ul").append('<li>Scooter</li>'); }); |
HTML
|
1 2 3 4 5 |
<ul> <li>Car</li> <li>Bike</li> <li>Cycle</li> </ul> |
Instead of .append() method, you can also use the .after() or .before() method to insert the specified content after or before a specified list element, respectively.
jQuery
|
1 2 3 |
$(document).ready(function() { $("ul li:last").before('<li>Scooter</li>'); }); |
HTML
|
1 2 3 4 5 |
<ul> <li>Car</li> <li>Bike</li> <li>Cycle</li> </ul> |
You can also use the .appendTo()/.prependTo() method, which is similar to the .append()/.prepend() method but has different syntax.
jQuery
|
1 2 3 4 5 |
$(document).ready(function() { $("<li>") .html('Scooter') .appendTo('ul'); }); |
HTML
|
1 2 3 4 5 |
<ul> <li>Car</li> <li>Bike</li> <li>Cycle</li> </ul> |
2. Using JavaScript
In pure JavaScript, you can create a <li> element using the createElement() method, and then append it to the list with Node.appendChild() method.
JS
|
1 2 3 4 |
var node = document.createElement('li'); node.appendChild(document.createTextNode('Scooter')); document.querySelector('ul').appendChild(node); |
HTML
|
1 2 3 4 5 |
<ul> <li>Car</li> <li>Bike</li> <li>Cycle</li> </ul> |
That’s all about adding an item to an HTML list in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)