来自完整HTML文档的jQuery对象

是否可以将完整的HTML文档解析为完整的jQuery对象? 当我尝试时,例如

var $tmp = $("title

test

"); console.log($tmp);

我明白了:

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

即一个将所有头部儿童与所有身体组合在一起的arrays。 是否不可能保留结构,包括html,head和body元素?

jquery剥离html和body,因为文档中只能有一个html和body。 布莱恩的答案是你能得到的最接近的答案,但仅限于非IE浏览器,因为IE不解析非html标签。

例如:

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

编辑:如何用div class = html / body替换html和body?

 var test = "
this is a test
"; test = test.replace(/(\/body|\/html)/i, "\/div") .replace(/html/i, "div class='html'") .replace(/body/i, "div class='body'"); console.log($(test));

我认为jQuery使用浏览器的本机innerHTML来创建那种情况下的元素。 因此,某些浏览器允许它,而其他浏览器则不允许。 我认为它适用于Firefox,但不适用于IE。

也许您可以尝试使用本机document.createElement()将它拼凑在一起。 不确定它是否会起作用。

一种破解方法是将’html’节点用“html”这个词替换为字符串。

 var tmp = 'title

test

'; tmp = tmp.replace(/html/g, 'html1'); console.log($(tmp));

我不确定我是否真的喜欢这个想法……