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?
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?
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/
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/
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();