Ban Istvan
Ban Istvan

Reputation: 101

jQuery addClass overrides previous element

$('#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

Answers (2)

Rick Hitchcock
Rick Hitchcock

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

Barmar
Barmar

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

Related Questions