jquery: .attr() fails for child element

116 views Asked by At

I'm going crazy staring at this. I need to change the attribute of an element, something which I have done many times before. But it fails. Now I can't even get jquery to show me the attribute that it has. Does it have to do with what is returned by find()?

var c = new_photo_div.find('[class = photo]')[0];
alert(c);
alert(new_photo_div.attr('class'));
alert(c.attr('class'));

The first alert correctly identifies the element: Object HTMLImageElement

The second alert correctly gives me the class of new_photo_div.

The third alert fails. No alert.

I think it should say: photo

3

There are 3 answers

0
YogeshWaran On BEST ANSWER

you are using new_photo_div.find('[class = photo]')[0] Dom element not jquery object . try this

$(c).attr('class');
0
nix On

It is because c is not a jQuery object. Remove [0] to assign a jQuery object to c.

0
Manjunath Manoharan On

In your browser console, an error would have come,

anyway, attr is a method of jQuery, dont do a [0],

Also you can use .prop instead of .attr if you are using a newer jquery library.