Sometimes we need to add li elements to ul dynamically based on some list. We can do this by using append() method.
Example- In the below example I have a list "users" and I want to display user names dynamically on page.
<html>
<head>
<title>Demo to show div</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function(){
var users = [
{ "id": "1", "userName": "John" },
{ "id": "2", "userName": "Jack" },
{ "id": "3", "userName": "Jenny" }
];
var userList = $("#userList");
userList.html("");
for ( var i = 0; i < users.length; i++) {
var user = users[i];
userList.append("<li id="+ user.id + ">"+ user.userName+ "</li>");
}
});
</script>
</head>
<body>
<ul id="userList">
</ul>
</body>
</html>
Hope this will help you :)
0 Comment(s)