I want to save the html element of a variable

I know how to use .html () to capture html inside my selected element, for example:

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

using something like

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

will capture my range as html. My problem is that I have

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

How can I assign 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 that I want, but its actually still an object.

+7
source share
5 answers

Try the following:

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

update:

 $("<div></div>").append($("#image")).html() 
+5
source

This can be easily done by wrapping the element in it and getting this HTML element in this way

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

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

Edit:

Without using jQuery you can do as below

 var el = document.getElementById('image'); html = el.outerHTML 
+2
source

Try creating this function in the 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(); 

The source is here .

0
source

outerHTML is not supported in firefox. You can 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 + " />"; } 
0
source

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

-one
source

All Articles