我有一个代表某个页面的文本。我需要将此 text 转换为 dom 对象,提取 body
元素并将其附加到我的 dom。
我使用以下代码转换文本并提取 body
元素:
$('body', $(text)).length
和:
$(text).filter('body').length
在这两种情况下,它都返回 0
...
最佳答案
jQuery 以非标准方式解析整个 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 是工作代码。
编辑:更改代码以显示直接追加和使用选择器。
关于javascript - 将表示为文本的 html 页面转换为 dom 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8493271/