Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access object in jquery (prevObject?)

A function in my WP plugin has just randomly (as far as I can tell) stopped working.

Here's the code in question:

window.send_to_editor = function(html) {
        var classes = jQuery('img',html).attr('class');
        var items = classes.split(" ");
        ... more stuff here
}

I've confirmed that the html variable is indeed an img html tag. Here's what firebug shows when I do a console.log of the object (console.log(jQuery('img',html));):

Object[]
context -> undefined
jquery -> "1.11.2"
length -> 0
prevObject -> Object[img.alignnone.size-full.wp-image-1234 name.jpg]

And the error it shows is classes is undefined.

I figure there's something wrong with the object I get, but this used to work recently and I'm not aware of any changes in the site that could have caused this.

I'd appreciate any input on this.

EDIT:

More info. This happens with two plugins which are supposed to be unrelated (made by different people). It happens when, after uploading an image to the server (or selecting a previously uploaded picture) you try to insert it into the post.

As I said before this error has appeared out of nowhere, it was working as intended a couple days ago. The only thing I can think of that has changed since then is the domain name, but I can't see how that could be related.

like image 681
mustieles Avatar asked May 25 '26 13:05

mustieles


2 Answers

The jQuery selector always returns a jQuery object, but when the length is 0 then no elements were found matching the selector that you provided. In your example you've confirmed that nothing is selected as the length of the jQuery object is 0. Perform a check whether an element was selected like this:

var $els = jQuery('img',html),
    classes;
if ($els.length) {
    classes = $els.attr("class");
}

Keep in mind that your DOM query is limited by what you pass in as the html parameter. If you simply want to find the images on the page do: var $els = jQuery('img');

like image 188
Konstantin Dinev Avatar answered May 27 '26 03:05

Konstantin Dinev


I finally managed to fix this; the key was parsing the html string variable into proper HTML, using jQuery.parseHTML(). Thanks to everyone who helped!

like image 36
mustieles Avatar answered May 27 '26 03:05

mustieles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!