16

.attr ('class') is undefined on jQuery ()

 3 years ago
source link: https://www.codesd.com/item/attr-class-is-undefined-on-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

.attr ('class') is undefined on jQuery ()

advertisements

I've got a problem with my jquery function in a wordpress theme. I've used exactly this function severeal times and it worked. The function returns the ID of an Image, that was uploaded via the wordpress uploader.

Here is the relevant part:

// extract the img-ID from class attribute
var jt = jQuery('img', html).attr('class');
alert(html);
alert(jt);
j1 = jt.split(' ');

Both alerts are only there to figure out, what happens. alert(html) returns this:

<img src="http://www.xyz.com/files/2012/03/stage.jpg" alt="" title="" width="1000" height="371" class="alignnone size-full wp-image-6" />

but alert(jt) returns "undefined".

Any Idea? It would be great, if you could help.


Your use of the context argument with your html variable is incorrect. Per the jQuery documentation, that context argument should be a DOM element, a document or a jQuery object. It cannot be a string of HTML.

If, what you have is a string and you want to make it into a DOM object, you can do that a number of ways.

This code will create a DOM object from the html string you have and then retrieve the class attribute from that DOM object.

var html = '<img src="http://www.xyz.com/files/2012/03/stage.jpg" alt="" title="" width="1000" height="371" class="alignnone size-full wp-image-6" />';
var item = jQuery(html);
var jt = item.attr('class');
alert(jt);
j1 = jt.split(' ');

You can see it work here: http://jsfiddle.net/jfriend00/phnED/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK