Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements within a variable using jQuery?

I'm trying to make a simple image browser for TinyMCE which I am using in my CMS. As part of this I need to detect whether the user has selected an existing image, so I can display the "edit" form instead of the "choose an image form".

var selected_html = ed.selection.getContent();
var $elem = $(selected_html);
console.log($elem);

The first function returns the user selected text from the editor window as a string of HTML. I then would like to use jQuery (although plain javascript is just ok too) to check if this string contains an img tag before subsequently grabbing the src and title attributes for editing.

Now I've got as far as getting the html to turn into an object. But after this I can't manage to search it for the img element. After reading this (How to manipulate HTML within a jQuery variable?) I tried:

$elem.find('img');

But it just comes out as an "undefined" object...

I think I'm missing something fairly obvious here (it is getting late), but after an hour I still can't figure out how to grab the img tag from the selection. :(

Many thanks in advance.

like image 490
Fourjays Avatar asked Sep 01 '10 23:09

Fourjays


1 Answers

Because the <img> is at the root of the jQuery object, you need to use .filter() instead of .find().

$elem.filter('img');

The .filter() method looks at the element(s) at the top level of the jQuery object, while .find() looks for elements nested in any of the top level elements.

If you're not sure beforehand where the target element will be, you could place the HTML into a wrapper <div> to search from. That way the HTML given will never be at the top.

var selected_html = ed.selection.getContent();
var $elem = $('<div>').html(selected_html);

var $img = $elem.find('img');
like image 92
user113716 Avatar answered Oct 09 '22 12:10

user113716