ajthinking
ajthinking

Reputation: 4588

Using class tree to delete specific HTML elements

How can I use vanilla JS to find and delete elements with a specific class X where the parent has class Y?

Example. Given

<div class="likes noise1">
   <div class="count noise2">
       42
   </div>
</div>
<div class="retweets noise3">
   <div class="count noise4">
       7
   </div>
</div>
<div class="messages noise5">
   <div class="count noise6">
       2
   </div>
</div>

I would like to delete the first two ".count" elements (the childs of ".likes" and ".retweets"). The messages div however should be left untouched.

I have tried using querySelectorAll which return a frozen NodeList and iterating it, without success.

Upvotes: 1

Views: 92

Answers (2)

Mamun
Mamun

Reputation: 68943

You can loop through all the elements to check the Element.className property of the Node.parentNode to remove the element like the following way:

document.querySelectorAll('.count').forEach(function(el){
  var classN = el.parentNode.className
  if(classN.includes('likes') || classN.includes('retweets'))
    el.remove();
});
<div class="likes">
   <div class="count">
       42
   </div>
</div>
<div class="retweets">
   <div class="count">
       7
   </div>
</div>
<div class="messages">
   <div class="count">
       2
   </div>
</div>

OR: You can simply simply specify both the classes as part of the selector, in which case you do not need to check the parentNode as the selector will give you only the elements inside the parents:

document.querySelectorAll('.likes > .count, .retweets > .count').forEach(function(el){
  el.parentNode.remove();    
});
<div class="likes">
   <div class="count">
       42
   </div>
</div>
<div class="retweets">
   <div class="count">
       7
   </div>
</div>
<div class="messages">
   <div class="count">
       2
   </div>
</div>

Upvotes: 2

enhzflep
enhzflep

Reputation: 13099

Another alternative, further to those already given is to keep an array of the css selector you'll need to find your targets. From there, it's just a simple matter of using querySelector so that the result is still live, albeit in a loop.

	"use strict";
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onWindowLoaded, false);

function onWindowLoaded(evt)
{
	var tgtSelectors = [ '.likes > .count', '.retweets > .count' ];
	tgtSelectors.forEach(removeBySelector);
}

function removeBySelector(curSelector)
{
	var tgt = document.querySelector(curSelector);
	while (tgt != undefined)
	{
		tgt.remove();
		tgt = document.querySelector(curSelector);
	}
}
<div class="likes">
	<div class="count">42</div>
</div>

<div class="retweets">
	<div class="count">7</div>
</div>

<div class="messages">
	<div class="count">2</div>
</div>

Upvotes: 0

Related Questions