1

In jQuery .html() method somehow do not return root element, for example:

var test = $('<root><val>hello world</val></root>');
var str = test.html(); // '<val>hello world</val>'

how can i get string with root tag included?

nukl
  • 10,073
  • 15
  • 42
  • 58
  • 2
    Possible duplicate of [jQuery - Get selected element's outer HTML](http://stackoverflow.com/questions/2419749/jquery-get-selected-elements-outer-html). Short answer: `clone()` the element, `wrap()` it, and call `html()` on the result. – Frédéric Hamidi Feb 09 '11 at 17:18

3 Answers3

2

You want the outerHTML property. Firefox doesn't support it, so you'll need to include a fix:

var str = test[0].outerHTML || $('<div>').append(test).html();

Working example: http://jsfiddle.net/Ub244/

user113716
  • 318,772
  • 63
  • 451
  • 440
  • Comparing your rep to mine, I'm clearly not in a position to advise you on etiquette, but do note that this is a clear duplicate of an existing question. – Phrogz Feb 09 '11 at 17:21
  • well, not EXACTLY. Explaining why this is happening only leads to the other question. – hunter Feb 09 '11 at 17:22
  • @Phrogz: The solutions posted in that duplicate don't utilize the `outerHTML` property. Anyway, most questions on SO these days seem to be dupes. If others want to close it, they may. – user113716 Feb 09 '11 at 17:23
  • will `test[0].outerHTML` ever not be `true`? Would that return `undefined` or `null`? – hunter Feb 09 '11 at 17:25
  • @hunter: In Firefox, it will be `undefined` ("falsey") because the property simply doesn't exist. As such, it will utilize the append method. – user113716 Feb 09 '11 at 17:27
1

because test IS the <root> element. You're creating it and selecting it.

html() will return the innerHTML for the element selected, which in this case is <root>


what you're looking for is the outerHtml.

See this question: Get selected element's outer HTML


You can get the root from the jQuery object and then call get it's outer html like so:

test.get(0).outerHTML;

working example: http://jsfiddle.net/U7Zdc/

Community
  • 1
  • 1
hunter
  • 62,308
  • 19
  • 113
  • 113
0

That's intended functionality. The docs for .html() state:

Get the HTML contents of the first element in the set of matched elements.

So, the variable test is a jQuery object pointing to the <root> element. Calling .html() on it will return HTML within the element. It's the same as using plain JavaScript's innerHTML propery.

To get <root> as well, you need to wrap test with another element and get the contents of it: $('<div>').append(test.clone()).remove().html();

simshaun
  • 21,263
  • 1
  • 57
  • 73