Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use remove() on multiple elements

Tags:

javascript

this: document.getElementsByClassName('warningmessage').remove(); doesn't work if you have multiple warningmessage elements on the page.

How can I just delete all elements with that class? do I have to use a for each? isn't there a command to deleteall()?

thanks for your tips!

like image 616
cmplieger Avatar asked Sep 19 '12 06:09

cmplieger


4 Answers

With plain JavaScript you can do this:

var nodes = document.getElementsByClassName('warningmessage');
for(var i = 0; i < nodes.length; i++){
  nodes[i].parentNode.removeChild(nodes[i]);
}

So you would first of all get the nodes you are interested in and afterwards iterate over them and remove them from their parents.

Sadly there is no forEach method on NodeList. However, you could this:

var nodes = document.getElementsByClassName('warningmessage');
[].forEach.call(nodes, function (node) {
  node.parentNode.removeChild(node);
});
like image 196
sdepold Avatar answered Oct 13 '22 13:10

sdepold


You need to use a loop. The below code shows how you write in "normal" javascript.

var elements = document.getElementsByClassName('warningmessage'),
    element;
while (element = elements[0]) {
  element.parentNode.removeChild(element);
}

The working demo.

like image 23
xdazz Avatar answered Oct 13 '22 12:10

xdazz


This would be super easier using JQuery:

$('.warningmessage').remove();

But it's not that hard when you do it without. getElementsByClassName can return a nodelist of items. So you'll just have to loop through the list and remove each item:

var list = document.getElementsByClassName("warningmessage");
for(var i = list.length - 1; i >= 0; i--)
{
    var n = list[i];
    n.parentNode.removeChild(n);
}
like image 41
GolezTrol Avatar answered Oct 13 '22 12:10

GolezTrol


You can try this

var elms= document.getElementsByClassName('warningmessage');
while(elms.length>0){
   for(var i = 0; i < elms.length; i++){
      elms[i].parentNode.removeChild(elms[i]);
   }
}​

http://jsfiddle.net/gBwjA/

like image 24
theintersect Avatar answered Oct 13 '22 13:10

theintersect