8

I know how to use .html() to grab the html inside of my selected element, like so:

<div id="outside>
    <span>hello</span>
</div>

using something like

var span = $('#outside).html();

will grab my span as the html. My problem is when I have

<img id="image" src="image.png">

How can I assign the html, as a string, to a variable? Using

var image = $('#image').html() 

gives me an empty string.

var image = $('#image')[0]

appears to get the html I want, but its actually still an object.

user883036
  • 113
  • 1
  • 1
  • 6

5 Answers5

5

Try this:

var myAwesomeHTML = $('#image')[0].outerHTML

update:

$("<div></div>").append($("#image")).html()
Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
2

This can be easily done by wrapping an element to it and getting theparent element's HTML like this

 var a=$('#image');
 a.wrap('<span class="ab"></span>');
 var htmlOfEle=$('.ab').html();

Here is the fiddle.. http://jsfiddle.net/CR2PD/2/ It may help you..

Edit:

Without using jQuery, you can do like below

var el = document.getElementById('image');
html = el.outerHTML
Exception
  • 8,111
  • 22
  • 85
  • 136
  • Better to do .outerHTML instead of adding some element around what you want. .outerHTML grabs the element AND what's inside of it. – Jeremy Miller Jan 14 '15 at 21:05
0

Try creating this function into Jquery core:

jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("&lt;p&gt;").append(this.eq(0).clone()).html();
}


$('#myTag').outerHTML();

Source here.

Marcelo Assis
  • 5,136
  • 3
  • 33
  • 54
0

outerHTML is not supported in firefox. You could try something like this :

var image = document.getElementById("image");

alert(outerHTML(image));

function outerHTML(elem){
    if (typeof elem.outerHTML !== "undefined")
    {
        return elem.outerHTML;
    }

    var s = "<" + elem.nodeName.toLowerCase();

    for (var i = 0; i < elem.attributes.length; i++)
    {
        s += " " + elem.attributes[i].name + '"' + escape(elem.attributes[i].value) + '"';
    }

    if (elem.hasChildNodes())
    {
        return s + ">" + elem.innerHTML + "</" + elem.nodeName + ">";
    }

    return s + " />";
}
Francis
  • 3,335
  • 20
  • 46
-1

To set the html for an element, you just use the .html() function, but pass it the string you want to set the html as: $('#image').html('<span>Hello</span>')

Joe C.
  • 1,538
  • 11
  • 14