JQuery |for loop create unique elements classes

Since you tagged jQuery you can use $.each method to loop through your array, and then use the id to add a class to each element Here’s a working solution.

var data = [{
    "id": 1,
    "name": "item 1"
}, {
    "id": 2,
    "name": "item 2"
}, {
    "id": 3,
    "name": "item 3"
}, {
    "id": 4,
    "name": "item 4"
}];

$.each(data, function (i, item) {
    $("#myList").append("<li class='"+item.id+"'>" + item.name + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="myList"></ul>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top