14

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.

Community
  • 1
  • 1
Fourjays
  • 537
  • 1
  • 8
  • 16
  • 1
    What do you do in order to get the `undefined` result you're getting? And can you post an example of the HTML that is being used to create the jQuery object? – user113716 Sep 01 '10 at 23:36
  • I'm just doing console.log (Chrome's debugger) at the moment. Whatever I do I end up with an object (a __proto__?) that has a context parameter set to "undefined" and a selector of "img". HTML being selected is straight forward - just an img ta, some bolded text and an img tag, etc. If I log $elem (as in the first bit of code) I get an object containing all HTML nodes within the selected bit of code. So that bit works fine. But then I can't manage to get jQuery to pick just the img element from this (via console.log($elem.find('img')); ). It always gives this "undefined" object. – Fourjays Sep 01 '10 at 23:49
  • The `.find()` method won't get the `` for you. See my answer below. – user113716 Sep 01 '10 at 23:55

2 Answers2

27

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');
user113716
  • 318,772
  • 63
  • 451
  • 440
0

Try to see what is really inside your $elem variable. Just do a console.log($elem) using both Firefox and Firebug and you should be able to manage quite alright! ;)

Frankie
  • 24,627
  • 10
  • 79
  • 121