在由字符串构成的DOM上调用jQuery.remove()

时间:2012-09-16 23:18:37

标签: javascript jquery html dom

html = '<h1>foo</h1><p>bar</p>';
virtual_dom = $(html);
console.log(virtual_dom);
// logs a data structure recognizable as a DOM with the h1 and p from the string

jQuery是否提供了从virtual_dom中删除段落的方法,以便console.log(virtual_dom)只记录一个只有h1标记的DOM,例如$('p').remove()但影响{{1}而不是浏览器呈现的实际文档?

2 个答案:

答案 0 :(得分:2)

使用.filter(),例如:

virtual_dom = $(html).filter(":not(p)");

这将从您的p 排除所有html aragraph。

<强> DEMO

答案 1 :(得分:0)

您的虚拟DOM是可遍历的,每个标记节点都是可移动的。

在FireBug或浏览器控制台中测试

var html = $('<div />');
html.append('<p /><p />').children(':last').text('Test');
console.log(html.html());
html.children(':first').remove();
console.log(html.html());