Find and remove a specific element using pure javascript

I have javascript that generates the following HTML

<div class='rightbox'> <div class'testBox'> </div> </div> 

Now I have a button that when clicked should remove the div class whos testbox . Now, although in this case it is not always that testbox is the first child in the rightbox .

So how do I find and delete it? and then after checking if it is present as a child of the rightbox ?

+6
source share
4 answers

Use, for example, querySelector() to find your item, and then a combination of parentNode and removeChild() to remove it.

 var el = document.querySelector( '.testBox' ); el.parentNode.removeChild( el ); 

Script example

+14
source
 var testBoxes = Array.prototype.slice.call(document.querySelectorAll('.testBox')); testBoxes.forEach(function(testBox) { testBox.parentNode.removeChild(testBox); }); 
+5
source
 var els = document.getElementsByTagName("div"); var el; for(var i = 0, ceiling = els.length; i < ceiling; i++) { el = els[i]; if(el.className == "testbox") { el.parentNode.removeChild(el); break; } } var presentAsChildWithinRightbox = false; for(var i = 0, ceiling = els.length; i < ceiling; i++) { el = els[i]; if(el.className == "rightbox") { var childNodes = el.childNodes; for(var j = 0, ceiling2 = childNodes.length; j < ceiling2; j++) { if(childNodes[j].className == "testbox") { presentAsChildWithinRightbox = true; j = ceiling2; i = ceiling; } } } } if(presentAsChildWithinRightbox) alert("A div with classname childbox has a child div with classname testbox"); else alert("A div with classname childbox does not have a child div with classname testbox"); 
+1
source

try it

 $(".rightBox").find("div").eq(0).remove(); $(".rightBox").find("div.testBox").remove(); 

Note. This is implemented using jQuery.

-6
source

Source: https://habr.com/ru/post/954501/


All Articles