Get Raw HTML of Node in JQuery
It's somewhat awkward to do:
var field = $("input"); // assuming there is but 1
var html = field.wrap("<div>").parent().html();
field.unwrap();
html()
is analagous to innerHTML
. There is no "standard" outerHTML
method. The above wraps the element you want in a temporary element and gets the innerHTML
of it.
This question is very old, but there is now an easy solution:
const html = $('input').prop('outerHTML');
Example string value of html
:
<input type="input">
Fiddle with it:
https://jsfiddle.net/u0a1zkL1/3
And, the technique mentioned in Optimae's comment also works:
const html = $('input')[0].outerHTML;
You can use:
var html = $('#parent')[0];
That will get the #parent node, then return the code of the first node returned (which will be the only one in this case).
Or you could create add an JQuery function like this:
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}
so you could do this:
$('input').outerHTML();
or
$('input').outerHTML("new html");
thanks to http://yelotofu.com/2008/08/jquery-outerhtml/