javascript - 删除子节点

标签 javascript

在我的 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>

引用文献:

关于javascript - 删除子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705858/

相关文章:

javascript - 使用 JavaScript 删除字符串中特定字符之后的所有内容

javascript - ajax post后用服务器的值更新原始对象

javascript - 删除 :hover using JavaScript (not using jQuery. .. 不要问)

javascript - 使用jquery取消确认后如何防止更改选择选项?

javascript - 在对象的嵌套数组中搜索字符串并设置 IsCheckedIn flag = true;

javascript - 更改检测在 Angular 2 的指令事件输出中不起作用

javascript - 禁用 Bootstrap 导航项单击事件

javascript - 如何访问另一个子组件中的插槽内容

javascript - 下一行丢失 Javascript 数组

javascript - 从对话框窗口Javascript中删除关闭按钮