Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add items to a unordered list <ul> using jquery

Tags:

json

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

  • , and create a href tag that links to the users page.
  • like image 795
    mrblah Avatar asked Jul 30 '09 18:07

    mrblah


    People also ask

    How do I add an item to a list in UL?

    Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element.

    How do I add something to an unordered list?

    You create an unordered list using the ul tag. Then, you use the li tag to list each and every one of the items you want your list to include. tag. This means that the li tag is the child of the ul tag.

    How can get ul id in jQuery?

    You can use $('li'). parent(). attr('id') to get the id of the parent element.

    What is UL in jQuery?

    The <ul> tag defines an unordered (bulleted) list. Use the <ul> tag together with the <li> tag to create unordered lists.


    1 Answers

    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>
    like image 153
    redsquare Avatar answered Oct 01 '22 10:10

    redsquare