删除子节点
Delete child nodes
在我的Greenhouse招聘公告栏上,有一些链接允许求职者从Dropbox上传简历。我需要删除Dropbox的链接。我可以识别document.getElementsByClassName("link-container")
的子节点,但谁能帮助删除data-source="dropbox"
的子节点?
<div class="link-container">
<a data-source="attach" href="#">Attach</a>
<a data-source="dropbox" href="#">Dropbox</a>
<a data-source="google-drive" href="#">Google Drive</a>
<a data-source="paste" href="#">Paste</a>
</div>
我建议;使用ES6 Array.from()
和箭头函数& &;如下:
// assuming there might be more than one element to be removed from
// the document, here we use document.querySelectorAll() to retrieve
// all <a> elements with a 'data-source' attribute equal to 'dropbox':
var targets = document.querySelectorAll('a[data-source=dropbox]');
// we convert the NodeList from document.querySelectorAll() into an
// an Array in order to use Array.prototype.forEach() to iterate
// over the elements:
Array.from(targets).forEach(
// now we use an Arrow function expression to access the
// current array-element of the array over which we're
// iterating (the 'dropboxLink' variable), and then
// perform the expression following the fat arrow ('=>')
// for each element of the array; finding the parentNode
// and removing that child from the parentNode:
dropboxLink => dropboxLink.parentNode.removeChild(dropboxLink));
<div class="link-container">
<a data-source="attach" href="#">Attach</a>
<a data-source="dropbox" href="#">Dropbox</a>
<a data-source="google-drive" href="#">Google Drive</a>
<a data-source="paste" href="#">Paste</a>
</div>
如果没有ES6,它就有点冗长了:
var targets = document.querySelectorAll('a[data-source=dropbox]');
// using function.prototype.call() to allow us to use
// Array.prototype.slice() on the array-like NodeList,
// converting it into an Array:
Array.prototype.slice.call(targets)
// using Array.prototype.forEach:
.forEach(function(dropboxLink) {
// 'dropboxLink' refers to the current Array element
// of the Array over which we're iterating.
// and, again, we remove the current Array-element
// from its parentNode:
dropboxLink.parentNode.removeChild(dropboxLink);
});
<div class="link-container">
<a data-source="attach" href="#">Attach</a>
<a data-source="dropbox" href="#">Dropbox</a>
<a data-source="google-drive" href="#">Google Drive</a>
<a data-source="paste" href="#">Paste</a>
</div>
引用:
-
Array.from()
. -
Array.prototype.forEach()
. -
Array.prototype.slice()
. - 箭头功能。
-
document.querySelectorAll()
. -
Function.prototype.call()
. -
Node.parentNode
. -
Node.removeChild()
.
相关文章:
- 删除HTML节点而不删除其子节点
- jQuery如何用1行来附加html和删除子节点
- 如何在JavaScript中删除子节点触发点击事件时的父节点
- Kendo TreeView-只向没有子节点的父节点添加删除图像图标
- 使用 JavaScript 从 XML 中删除子节点
- jQuery - 如何循环删除仅某些子节点
- 如何从 Javascript 对象中删除所有子节点
- 从 JSON 中删除子节点
- 如何在 jstree 中删除所选节点的子节点
- 可以't删除所有子节点
- DOM Javascript正在删除子节点
- 如何使用jquery删除树视图子节点
- 如何删除父节点及其所有子节点
- 从组paperJS中删除特定的子节点
- Firebase根据子值删除节点
- Firebase Web update()删除所有其他子节点
- KinteticJS -销毁节点,无限while循环,因为子节点没有被删除
- 删除子节点错误
- 删除子节点
- 在javascript dom中,删除所有子节点会产生错误