2016-09-26 10 views
0

私のグリーンハウスのジョブボードには、DropboxからCVをアップロードするためのリンクがいくつかあります。 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>

答えて

2

私は、次のES6 Array.from()と矢印機能–を使用して–をお勧めしたい:ES6なし

// 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>

が、それはもう少し冗長です:

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>

参考文献:

+0

ES6オプションは私には利用できませんが、ES6以外のものは完璧に動作しました - ありがとう! – user3401641