JQuery object from full HTML document

Is it possible to parse a complete HTML document as a complete jQuery object? When I try, for example,

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 that unites all the head children with the whole body. Can't keep structure including html, head and body elements?

+2
source share
3 answers

jquery removes html and body since there can only be one html and body in a document. The Brian answer is the closest you can get, but only in a browser without IE, since IE does not parse the tag without html.

For instance:

 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)); 
+1
source

I think jQuery uses the native browser innerHTML to create elements in this situation. Thus, some browsers allow this, others do not. I think this will work in Firefox, but not in IE.

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

0
source

The type of hack will be that the string replaces 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 ...

0
source

Source: https://habr.com/ru/post/1343972/


All Articles