jQuery: I can not change the CSS color of an element after using append ()

advertisements

I have used jQuery's append() command to create a set of DIVs from an array.

After doing a simple JSON request, I would now like to change the color of the text within the DIV using the css() command. However, I cannot seem to get it to work.

Here is a cross-section of the code I have written:

function createList(myArray){
    $.each(myArray,function(index,item){
        $("#results_panel").append('<div id="result_'+item+'">'+item+'</div>');
        doSomeStuff(item);
    });
}

function doSomeStuff(item){
    var urlJSON="file_upload.php?ip_address="+item;
    $.getJSON(urlJSON,function(json){
        if (json.result == "true") {
            $("#result_"+item).css("color","#00FF00");
        } else {
            $("#result_"+item).css("color","#FF0000");
        }
    });
}

If I use document.getElementByID.("result_"+item).style.color this will work, however.

Can anyone tell me what I am doing wrong here? I'm fairly new to jQuery, so apologies if this is a really obvious question.


Your problem is the values that you are using as the ID of your elements. Have a look at this fiddle ->

The DOM method will allow a name with an IP in it. jQuery, however, interprets the .s in the IP address as the beginning of a class selector, and thus does not select anything.

Have a look at these two demos:

By replacing the .s in the IP with underscores, the ID becomes valid for jQuery selection, and the color will be correctly applied.