Reputation: 101
$('#naiveComments').append("<ul id='newList'></ul>").css("color", "white");
var keys = Object.keys(result);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
console.log(result[key]);
if (result[key] == 1)
{
$("#newList").append("<li>" + key + "</li>").addClass("positive");
}
else if (result[key] == -1)
{
$("#newList").append("<li>" + key + "</li>").addClass("negative");
}
}
My result[key]
field stores a value of 1,0 and -1. Based on this value I would like to add a specific class to the current <li> </li>
element, however the last addClass will be the final one. I'm aware of the fact that in my case this sets the class for every <li>
element but I'm unable to find a way in which I could set different classes to different <li>
elements.
Upvotes: 1
Views: 65
Reputation: 35670
You want appendTo, not append
:
This adds a class to #newList
:
$("#newList").append("<li>" + key + "</li>").addClass("positive");
This adds a class to a new li
in #newList
:
$("<li>" + key + "</li>").appendTo("#newList").addClass("positive");
Upvotes: 4
Reputation: 781503
The result of .append()
is the element you're appending to (so you can chain multiple appends), not the element you added. You need to create the new element as the argument, and add the class to that.
$("#newlist").append(
$("<li>", {
text: key,
"class": "positive"
})
);
Upvotes: 0