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是赢家! http://jsperf.com/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立即进行!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值