jquery: .attr() fails for child element
-
07-07-2021 - |
Question
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
Solution
you are using new_photo_div.find('[class = photo]')[0]
Dom element not jquery object .
try this
$(c).attr('class');
OTHER TIPS
It is because c
is not a jQuery object. Remove [0]
to assign a jQuery object to c
.
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.