Reaversword
Reaversword

Reputation: 167

JQuery doesn't reads dynamic created element attributes

Well, I think this gonna be a simple question, but I'm unable to realize how Jquery loses/is not able to find attributes of the element:

Javascript:

for (var i=0; i<=10; i++)
{
    Cells[i]=document.createElement('div');
    Cells[i].id = "Cell"+String(i);
    Cells[i].className = "CellClass";
    if (i==0)//Let's look the fist one (neverminds which one).
    {
        alert(Cells[0].className);//This would alert: "CellClass" (without quotes).
        alert($("#Cell0").className);//This would alert: "undefined" (without quotes).
        //Another way:
        alert($(Cells[0]).className);//This would alert: "undefined" (without quotes).
    }
}

for the question, class .CellClass is not relevant itself, neverminds which attributes define.

What am I not understanding?

Upvotes: 0

Views: 632

Answers (3)

Alnitak
Alnitak

Reputation: 340055

Not withstanding Arun's answer about the difference between jQuery objects and DOM objects, you'll also find that $("#Cell0") won't actually work until #Cell0 has actually been placed in the DOM, by adding it to a parent node.

Upvotes: 3

Manish Jangir
Manish Jangir

Reputation: 5437

alert($("#Cell0").attr('class'));

Will work

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

$(Cells[0]) returns a jQuery wrapper object not a dom element reference so it does not have properties like className.

You can use any one of the following method

Cells[0].className
$(Cells[0]).prop('className')
$(Cells[0]).attr('class')

Also make sure that the element is added to the dom structure before the jQuery selector $("#Cell0") is executed else the element will not be found in the dom lookup

Upvotes: 6

Related Questions