我有一个文本表示某个页面。我需要将此文本转换为dom对象,提取body
元素并将其附加到我的dom中。将html页面表示为文本到dom对象
我用下面的代码将文本转换并提取body
元素:
$('body', $(text)).length
和:
$(text).filter('body').length
在返回0
这两种情况下...
测试:http://jsfiddle.net/wEyvr/1/
我有一个文本表示某个页面。我需要将此文本转换为dom对象,提取body
元素并将其附加到我的dom中。将html页面表示为文本到dom对象
我用下面的代码将文本转换并提取body
元素:
$('body', $(text)).length
和:
$(text).filter('body').length
在返回0
这两种情况下...
测试:http://jsfiddle.net/wEyvr/1/
jQuery是p以非标准方式解析整个HTML,因此$(html)
无法按预期工作。
可以使用正则表达式和工作从那里提取body标签的内容:
// get the content of the body tags
var body = $(text.match(/<body[\s\S]*?>([\s\S]*?)<\/body>/i)[1]);
// append the content to our DOM
body.appendTo('body');
// bonus - to be able to fully use find -> we need to add single parent
var findBody = $("<body />").html(body.clone());
// now we are able to use selectors and have fun
findBody.find("div.cls").appendTo('body');
HERE是工作代码。
编辑:更改代码以显示直接追加和也使用选择器。
事情是这样的:
var ifr = $("<iframe>"),
doc = ifr.appendTo("body")[0].contentWindow.document,
bodyLength;
doc.open();
doc.write(text);
doc.close();
bodyLength = ifr.contents().find("body").length;
ifr.remove();
alert(bodyLength);
你能不能把你的文字变成的jsfiddle?你的第一种方法看起来有效 – StuperUser 2011-12-13 17:15:08
第二种方法看起来像是使用find而不是filter来有效。 – kojiro 2011-12-13 17:17:37