1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java dom 获得子元素_在JavaScript中删除DOM节点的所有子元素

java dom 获得子元素_在JavaScript中删除DOM节点的所有子元素

时间:2020-01-07 08:21:55

相关推荐

java dom 获得子元素_在JavaScript中删除DOM节点的所有子元素

我将如何删除JavaScript中DOM节点的所有子元素?

说我有以下(丑陋的)HTML:

hello

world

我抓住了我想要的节点,如下所示:

var myNode = document.getElementById("foo");

我怎样才能删除foo的子代,只剩下

我可以做:

myNode.childNodes = new Array();

还是应该使用removeElement某种组合?

我希望答案直接是DOM; 如果您还提供jQuery答案以及仅DOM答案,则需要加分。

#1楼

为了回应DanMan,Maarten和Matt。 克隆节点以设置文本确实是我的结果中可行的方法。

// @param {node} node

// @return {node} empty node

function removeAllChildrenFromNode (node) {

var shell;

// do not copy the contents

shell = node.cloneNode(false);

if (node.parentNode) {

node.parentNode.replaceChild(shell, node);

}

return shell;

}

// use as such

var myNode = document.getElementById('foo');

myNode = removeAllChildrenFromNode( myNode );

这也适用于不在dom中的节点,这些节点在尝试访问parentNode时返回null。 此外,如果您需要安全,则在添加内容之前节点为空,这确实很有帮助。 考虑下面的用例。

// @param {node} node

// @param {string|html} content

// @return {node} node with content only

function refreshContent (node, content) {

var shell;

// do not copy the contents

shell = node.cloneNode(false);

// use innerHTML or you preffered method

// depending on what you need

shell.innerHTML( content );

if (node.parentNode) {

node.parentNode.replaceChild(shell, node);

}

return shell;

}

// use as such

var myNode = document.getElementById('foo');

myNode = refreshContent( myNode );

我发现在替换元素内的字符串时此方法非常有用,如果您不确定节点将包含的内容,而不用担心如何清理混乱,请重新开始。

#2楼

最快的...

var removeChilds = function (node) {

var last;

while (last = node.lastChild) node.removeChild(last);

};

编辑:很明显,Chrome在firstChild和lastChild之间没有性能差异。 最佳答案显示了一个很好的性能解决方案。

#3楼

innerText是赢家! /innerhtml-vs-removechild/133 。 在所有先前的测试中,父节点的内部dom在第一次迭代时都被删除,然后将innerHTML或removeChild应用于空div。

#4楼

var empty_element = function (element) {

var node = element;

while (element.hasChildNodes()) { // selected elem has children

if (node.hasChildNodes()) { // current node has children

node = node.lastChild; // set current node to child

}

else { // last child found

console.log(node.nodeName);

node = node.parentNode; // set node to parent

node.removeChild(node.lastChild); // remove last node

}

}

}

这将删除元素内的所有节点。

#5楼

我看到人们在做:

while (el.firstNode) {

el.removeChild(el.firstNode);

}

然后有人说使用el.lastNode更快

但是我认为这是最快的:

var children = el.childNodes;

for (var i=children.length - 1; i>-1; i--) {

el.removeNode(children[i]);

}

你怎么看?

ps:这个话题对我来说是个救命稻草。 我的Firefox插件被拒绝了,因为我使用了innerHTML。 长期以来一直是习惯。 那我就这样 我实际上注意到了速度差异。 在加载时,innerhtml花费了一段时间进行更新,但是通过addElement立即进行!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。