user984003
user984003

Reputation: 29527

jquery: .attr() fails for child element

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

Upvotes: 0

Views: 118

Answers (3)

Manjunath Manoharan
Manjunath Manoharan

Reputation: 4617

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.

Upvotes: 0

nix
nix

Reputation: 3302

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

Upvotes: 2

YogeshWaran
YogeshWaran

Reputation: 2281

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

$(c).attr('class');

Upvotes: 1

Related Questions