2

Is it possible to parse a complete HTML document as a complete jQuery object? When I try, e.g.

var $tmp = $("<html><head><title>title</title></head><body><p id='test'>test</p></body></html>");
console.log($tmp);

I get:

[+] [title, p#test] []

i.e. an array combining all of the head's children with all of the body's. Is it not possible to retain the structure, including the html, head, and body elements?

Bobby Jack
  • 15,689
  • 15
  • 65
  • 97

3 Answers3

1

jquery strips out html and body as there can only be one html and body in a document. Brian's answer is the closest you can get, but only on non IE browser as IE don't parse non html tag.

For example:

var test = "<test>This is it</test>";
alert($(test).html());  // display This is it in non IE browser (working in 8-9?).

EDIT: How about replacing html and body with div class=html/body?

var test = "<html><body><div>this is a test</div></body></html>";
test = test.replace(/(\/body|\/html)/i, "\/div")
           .replace(/html/i, "div class='html'")
           .replace(/body/i, "div class='body'");
console.log($(test));
Jules
  • 1,423
  • 13
  • 22
  • You can certainly create additional `html` and `body` elements in the **DOM**, at least in some implementations (only tested in WebKit, using `document.createElement`). You can even append them to other elements (`element.appendChild`). jQuery strips these out because it's absurdly rare in common use cases that developers will want to do this, but quite common that they'll want to just dump a server response from an Ajax call into a `div` somewhere. – eyelidlessness Dec 23 '10 at 09:41
  • @eylidlessness, you are right, I tested in FF to append a second body to html (not inside a div) and the second body is displayed, but in IE, the second body is not displayed. I guess, I'll stick with the "proper" html construct :). – Jules Dec 23 '10 at 23:15
0

I think jQuery uses the browser's native innerHTML to create the elements in that situation. As such, some browsers allow it, others don't. I think it will work in Firefox, but not IE.

Perhaps you could try piecing it together using the native document.createElement(). Not sure if it will work.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • Thanks, Patrick. No luck in Firefox. What I'm really trying to do is just use jQuery's core functionality to parse an HTML document fetched via AJAX. It looks like I'll have to do a BIT more work myself ... – Bobby Jack Nov 11 '10 at 15:26
  • @Bobby - You're welcome. Yeah, likely it will take a little manual parsing, depending on what you're trying to achieve. – user113716 Nov 11 '10 at 16:07
0

A kind of hack would be to string replace the 'html' nodes with something other than the word 'html'.

var tmp = '<html><head><title>title</title></head><body><p id="test">test</p></body></html>';
tmp = tmp.replace(/html/g, 'html1');
console.log($(tmp));

I'm not sure I really like this idea though...

Brian Flanagan
  • 4,612
  • 5
  • 29
  • 38