Reputation: 1321
This may have been asked a lot in SO but I'm unable to make it work.
As the title says I need to append <ul> <li>
dynamically inside one element.
The method addUsers()
is called everytime there is an update to json.
Html:
<div id="users"></div>
Javascript:
function addUsers() {
var users = $('#users'); // div element
users.html(''); // clears the div everytime it come inside addUsers() method
users.append('<ul>');
for (var i = 0; i < json.users.length; i++) {
users.append('<li><a href="#"><span class="user-list">'+json.users[i]+'</span></a></li>');
}
}
Excepted Output:
<div id="users">
<ul>
<li><a href="#"><span class="user-list">User1</span></a></li>
<li><a href="#"><span class="user-list">User2</span></a></li>
<li><a href="#"><span class="user-list">User3</span></a></li>
</ul>
Actual Output:
<div id="users">
<ul></ul> //UL is ending here
<li><a href="#"><span class="user-list">User1</span></a></li>
<li><a href="#"><span class="user-list">User2</span></a></li>
<li><a href="#"><span class="user-list">User3</span></a></li>
</div>
I must be doing something wrong. Appreciate any pointers. Thanks!
Upvotes: 2
Views: 3731
Reputation: 1
(function () {
var i = 0;
var users_div = $('#users');
users_div.html('');
var child_ul = $('<ul></ul>').appendTo(users_div);
for (i; i < 3; i += 1) {
var child_li = $('<li></li>').appendTo(child_ul);
var child_a = $('<a></a>').attr({
href: '#'
}).appendTo(child_li);
var child_span = $('<span></span>').attr({
class: 'userlist'
});
child_span.appendTo(child_a);
}
})();
Upvotes: 0
Reputation: 1321
Not able to format my code snippet in comment section so adding it in Answer. First of all thanks @Rajaprabhu @adeneo and others for such quick rsponse.
Here is the modified code. Please let me know if that is correct.
var users = $('#users'); // div element
users.html(''); // clears the div everytime it come inside addUsers() method
users.append('<ul>');
var xUl = users.find('ul');
for (var i = 0; i < json.users.length; i++) {
xUl.append('<li><a href="#"><span class="user-list">'+json.users[i]+'</span></a></li>');
}
Upvotes: 0
Reputation: 119
try this:
var temp = $('<ul> </ul>');
//LOOP
temp.append('<li><a href="#"><span class="user-list">'+json.users[i]+'</span></a></li>')
//END LOOP
users.html(temp)
Upvotes: 0
Reputation: 318162
function addUsers() {
var users = $('#users').empty(),
ul = $('<ul />');
$.each(json.users, function(_, user) {
var li = $('<li />'),
a = $('<a />', {href : '#'}),
sp = $('<span />', {'class' : 'user-list', text : user});
ul.append( li.append( a.append(sp) ) );
});
users.append(ul);
}
Upvotes: 2
Reputation: 67187
You are actually appending the li
elements to the Div
element. But in your context ul
is present inside of that Div
element. So you have to use .find()
function to select that.
Try,
var xUl = users.find('ul');
for (var i = 0; i < json.users.length; i++) {
xUl.append('<li><a href="#"><span class="user-list">'+json.users[i]+'</span></a></li>');
}
Upvotes: 4