Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Jan

like image 949
jabre Avatar asked Mar 05 '12 23:03

jabre


People also ask

What is. attr in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to get property value in jQuery?

jQuery prop() Method Note: The prop() method should be used to retrieve property values, e.g. DOM properties (like tagName, nodeName, defaultChecked) or your own custom made properties. Tip: To retrieve HTML attributes, use the attr() method instead.


2 Answers

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/

like image 64
jfriend00 Avatar answered Sep 28 '22 08:09

jfriend00


Your problem is here:

jQuery('img', html)

The context is html and apparently html is an image so you're looking for a img inside an img which it won't find.

EDIT:
If html is <img src="http://www.xyz.com/files/2012/03/stage.jpg" alt="" title="" width="1000" height="371" class="alignnone size-full wp-image-6" /> then you can grab the class like this:

var klass = $(html).attr('class');

// You could do this to create an array of all classes
var klasses = $(html).attr('class').match(/\S+/g);
like image 44
elclanrs Avatar answered Sep 28 '22 06:09

elclanrs