Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and remove the parentNode of querySelectorAll

Tags:

javascript

I am trying to target the parent node, which is a div of a link tag(a) in my code, I have tried target.parentNode but that does not work, maybe as I am using querySelectorAll?. My code so far is:

  function remove() {
    var target = document.querySelectorAll('a[data-type="data"]'), i;
     for (i = 0; i < target.length; i++) {
       if (target.length > 1) {
        target[i].remove();
       }
     }
  }
  remove();

Html:

<div class="carousel-slide">
   <a data-type="data" data-type="image">
   <img class="img-responsive" src="./285-603.jpg">
   </a>
</div>

Any idea's?

like image 539
Sole Avatar asked Jul 16 '20 23:07

Sole


Video Answer


2 Answers

You could utilize for...of to loop through all elements that were found, then call parentNode.remove() on them:

function remove() {
  var anchors = document.querySelectorAll("a[data-type='data']");
  console.log("before", anchors.length);

  // use `for...of` to iterate through all anchor tags
  for (var anchor of anchors) {
    // remove the parent node
    anchor.parentNode.remove();
  }
  
  console.log(
    "after", 
    document.querySelectorAll("a[data-type='data']").length
  );
}
remove();
<div class="carousel-slide">
  <a data-type="data" data-type="image">
    <img
      class="img-responsive"
      draggable="false"
      src="./285-602.jpg"
    />
  </a>
</div>
<div class="carousel-slide">
  <a data-type="data" data-type="image">
    <img
      class="img-responsive"
      draggable="false"
      src="./285-603.jpg"
    />
  </a>
</div>

Reference:

  • for...of - MDN
like image 136
goto Avatar answered Oct 02 '22 02:10

goto


You need to use parentNode.

const remove = () => {
  const target = document.querySelectorAll('a[data-type="data"]');
  for (let i = 0; i < target.length; i++) {
    target[i].parentNode.remove();
  }
};
remove();

like image 33
Ahmed ElMetwally Avatar answered Oct 02 '22 04:10

Ahmed ElMetwally