Possible Duplicate:
Remove all elements with a certain class with JavaScript
As title, google search gives me all jquery results. Is there a method that does this? ex.
<div id="container">
<div class="dontdelete">...</div>
<div class="deleteme>...</div>
<div class="dontdelete">...</div>
<div class="deleteme>...</div>
<div class="dontdelete">...</div>
<div class="deleteme>...</div>
</div>
Is there a method in pure javascript to delete all child with "deleteme" class? Thanks in advance.
Since element.getElementsByClassName
returns a live node list, you need to loop through the list in a certain way (since removing them from the DOM removes them from the list as well). Try something like this:
var container = document.getElementById("container");
var elements = container.getElementsByClassName("deleteme");
while (elements[0]) {
elements[0].parentNode.removeChild(elements[0]);
}
DEMO: http://jsfiddle.net/sR2zT/1/
Or you could use something like element.querySelectorAll
to select the elements, where you can do things like this:
document.querySelectorAll("#container .deleteme")
// or
document.getElementById("container").querySelectorAll(".deleteme")
In this scenario, you don't need to do special looping, because querySelectorAll
doesn't contain a live node list.
References:
getElementsByClassName()
- https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName
querySelectorAll()
- https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
removeChild()
- https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild
You are probably looking for getElementsByClassName
to get all your elements. Then you can use something like removeChild
to delete the nodes.
var elements = document.getElementById("container")
.getElementsByClassName("deleteme");
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
Working example: http://jsfiddle.net/ja4Zt/1/
Browser support:
The only caveat with this solution is that it has limited support in IE. According to this table, getElementsByClassName
was implemented in IE as of version 9.
To bridge this, you could select all nodes that are child of the element with ID container, loop over them and check if they have the class "deleteme", and only then delete them.
This version avoids having to use .getElementsByClassName()
which as others have mentioned is not supported in certain IE versions.
var divs = document.getElementById("container").childNodes;
var i = divs.length;
while( i-- ) {
if( divs[i].className && divs[i].className.indexOf("deleteme") > -1 ) {
divs[i].parentNode.removeChild( divs[i] );
}
}
This also traverses the resulting array backwards so deleting nodes doesn't affect the next iteration.
Fiddle here
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