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
?
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.
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.
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.
Use element. remove() to remove an element from the DOM. Remove all children from an element with element. children.
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.
var testBoxes = Array.prototype.slice.call(document.querySelectorAll('.testBox'));
testBoxes.forEach(function(testBox) {
testBox.parentNode.removeChild(testBox);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With