How to add items to a unordered list <ul> using jquery
In my json response, I want to loop through it using $.each and then append items to a <ul></ul>
element.
$.each(data, function(i, item) {
// item.UserID
// item.Username
}
I want to add a
The most efficient way is to create an array and append to the dom once.
You can make it better still by losing all the string concat from the string. Either push multiple times to the array or build the string using += and then push but it becomes a bit harder to read for some.
Also you can wrap all the items in a parent element (in this case the ul) and append that to the container for best performance. Just push the '<ul>'
and '</ul>'
before and after the each and append to a div.
data = [
{
"userId": 1,
"Username": "User_1"
},
{
"userId": 2,
"Username": "User_2"
}
];
var items = [];
$.each(data, function(i, item) {
items.push('<li><a href="yourlink?id=' + item.UserID + '">' + item.Username + '</a></li>');
}); // close each()
$('#yourUl').append(items.join(''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="yourUl">
</ul>
I decided to take redsquare's excellent answer and improve upon it a bit. Rather than adding HTML, I prefer to add jQuery objects. That way, I don't have to worry about escaping for HTML and what not.
In this example, data
contains an array of objects, parsed from JSON. Each object in the array has a .title
property. I use jQuery's each
function to loop through them.
var items=[];
$(data).each(function(index, Element) {
items.push($('<li/>').text(Element.title));
});
$('#my_list').append.apply($('#my_list'), items);
I push a new jQuery object onto the items array, but with method chaining I can set properties ahead of time, such as .text
.
I then append the array of objects to the list <ul id="my_list">
using Lars Gersmann's method.
Get the <ul>
using jQuery selector syntax and then call append
:
$("ul#theList").append("<li><a href='url-here'>Link Text</a></li>");
See jQuery docs for more information.
$.each(data, function(i, item) {
var li = $("<li><a></a></li>");
$("#yourul").append(li);
$("a",li).text(item.Username);
$("a",li).attr("href", "http://example.com" + item.UserID);
}