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!
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!
Share Improve this question asked Sep 19, 2012 at 6:06 cmpliegercmplieger 7,35116 gold badges56 silver badges84 bronze badges 4 |5 Answers
Reset to default 9With 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);
});
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.
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);
}
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/
I have this problem before and I end up in this algorithm.
function removeElement(target) {
if(target.hasOwnProperty('length')) {
for(i=0; i<target.length; i++) {
removeElement(target[i]);
}
} else {
target.parentNode.removeChild(target);
}
}
and then you call the function like this:
removeElement(document.getElementById('the-id'));
or if you want to remove an HTML collection of elements then you call the function in this way:
removeElement(document.getElementsByTagName('tag-name'));
.remove()
is jQuery syntax, if you're using jQuery, you can just do$('.warningmessage').remove()
to remove all instances. – Korvin Szanto Commented Sep 19, 2012 at 6:09getElementsByClassName
returns aNodeList
. You have to iterate over this list and remove each node. MDN is a very helpful resource: developer.mozilla.org/en-US/docs/DOM – Felix Kling Commented Sep 19, 2012 at 6:12