Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and remove specific element using pure javascript [closed]

I have javascript that generates the following HTML

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

 </div>


</div>

Now i have a button that when pressed should remove the div whos class is testbox. Now even though it is in this case it is not always that the testBox is the first child within the rightbox.

So how do i find and remove it? and then afterwards test if it is present as a child within the rightbox?

like image 230
Marc Avatar asked Sep 24 '13 12:09

Marc


People also ask

Is there a remove method in JavaScript?

Removing JavaScript Array items is important to managing your data. There is not a single 'remove' method available, but there are different methods and techniques you can use to purge unwanted array items.

How do you remove an element in JavaScript?

In JavaScript, an element can only be deleted from its parent. To delete one, you have to get the element, find its parent, and delete it using the removeChild method.

What does querySelectorAll () method returns?

Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

How do I remove DOM element?

Use element. remove() to remove an element from the DOM. Remove all children from an element with element. children.


2 Answers

Use, e.g., querySelector() to find your element and then a combination of parentNode and removeChild() to delete it.

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

Example Fiddle


Edit 2018:

In the meanwhile support for remove() has landed (In all browsers, but IE), so the above code can be reduced to the following:

document.querySelector( '.testBox' ).remove();

Note, that you should check, whether the selected node actually exists. Otherwiese both snippets will throw an error.

like image 88
Sirko Avatar answered Nov 04 '22 20:11

Sirko


var testBoxes = Array.prototype.slice.call(document.querySelectorAll('.testBox'));

testBoxes.forEach(function(testBox) {
    testBox.parentNode.removeChild(testBox);
});
like image 30
Samuli Hakoniemi Avatar answered Nov 04 '22 20:11

Samuli Hakoniemi