Remove all children from node with same class, pure js

Possible duplicate:
Delete all elements with a specific class using JavaScript

As a title, google search gives me all jquery results. Is there a way that does this? e.g.

<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 remove the entire child with the class "deleteeme"? Thanks in advance.

+4
source share
4 answers

Since element.getElementsByClassName returns a live node list, you need to go through the list in a certain way (since removing them from the DOM also removes them from the list). 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 can use something like element.querySelectorAll to select elements where you can do things like this:

 document.querySelectorAll("#container .deleteme") // or document.getElementById("container").querySelectorAll(".deleteme") 

In this case, you do not need to do a special loop, because querySelectorAll does not contain a live node list.

Literature:

+10
source

You are probably looking for getElementsByClassName to get all your elements. Then you can use something like removeChild to remove 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 been implemented in IE since version 9.

To eliminate this, you can select all nodes that are children of an element with an ID container, iterate over them and check if they have a class "removeeme", and only then remove them.

+3
source

This version avoids using .getElementsByClassName() , which, as others have pointed out, is not supported in some versions of IE.

 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] ); } }​ 

It also moves the resulting array backward, so deleting nodes does not affect the next iteration.

Feed here

+2
source
 var divs = document.getElementsByClassName("deleteme"); for (var idx = 0; idx != divs.length; idx++) { var div = divs[idx]; while (div.firstChild) div.removeChild(div.firstChild); } 

-1
source

All Articles