views:

151

answers:

3

I have used $("#parent").html() to get the inner html of #parent, but how do I get the html of the parent itself?

The use case is, I grab an input node like this:

var field = $('input');

I would like to be able to get the raw html of that node (<input type='text'>) with something like field.html(), but that returns empty. Is this possible?

+2  A: 

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.

cletus
A: 

try

var field = $('input');
$('<div>').append(field).html()

quick demo

Reigel
+1  A: 

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/

Richard
Isn't `clone()` a problem due to event handlers?
cletus