jQuery: <IMG/> element on-the-fly

3.8k Views Asked by At

Here is the problematic part of my code, run inside .each(function(){ });

$('img','<div>'+ed.selection.getContent({format: 'html'})+'</div>').each(function(){  
  $img=$('<img/>').attr('src',$(this).attr('src'));
  alert($('<p>'+$img+'</p>').html());
  if ($(this).attr('height').length>0){
    $img.attr('height',$(this).attr('height'));
  }
  if ($(this).attr('width').length>0){
    $img.attr('width',$(this).attr('width'));
  }
  alert($img.html());
});

First, i'm working with the selected tinyMCE content in html format which is fust fine as jQuery recognizes it properly. $img.html() returns empty value, not undefined but just blank. Tested both FF 3.6 and IE8. Can someone explain, please?

4

There are 4 best solutions below

0
On BEST ANSWER

The html() function only returns the contents of the element. Since <IMG> is technically empty, you get an empty string.

If you had this:

<span>The text</span>

and you asked for $span.html(), you'd get just The text, without the enclosing tags.

0
On

.html() gives you the innerHTML of an element i.e. what's inside it. An <img> doesn't have anything inside it - it's an empty element.

You have the right idea by wrapping it and taking the innerHTML of that.

0
On

An image element doesn't have any inner HTML, therefore the method can't return any.

0
On

If you are interested in accessing the <img>'s content then have a look at Question number 298049