Skip to content Skip to sidebar Skip to footer

Remove Element From Dom

I have a code:
  • Jakub
  • Vinnie
  • David
  • &

Solution 1:

You already have the parent node from your original getElementsByClassName, and you have your child through the loop that you've just performed.

As such, it's simple:

for (var i=0; i< mates.childNodes.length; i++){
  if(mates.children[i].innerHTML == 'Vinnie'){
    alert("Got you! ID "+mates.children[i].id)
    mates.removeChild(mates.children[i]);
    break;
  }
}

For the sake of completeness (and to prevent further arguing in comments :P), if you are in fact potentially deleting multiple "Vinnie"'s from your list, then it would be better to make a list of those children you want to delete, then delete them after like so:

var toDelete=[],
    i;

for (i=0; i< mates.childNodes.length; i++){
  if(mates.children[i].innerHTML == 'Vinnie'){
    alert("Got you! ID "+mates.children[i].id)
    toDelete.push(mates.children[i]);
  }
}

for (i=0; i<toDelete.length; i++){
  mates.removeChild(toDelete[i]);
} 

Solution 2:

You don't need that parent variable. Delete it using this:

mates.removeChild(mateToDelete);

Fiddle: http://jsfiddle.net/3XeM5/2/

I also modified your for-loop to use:

for (var i=0; i< mates.children.length; i++){ 

The length of this (children.length) is 3, the length of childNodes is 7, so if nothing is found the loop will break!

Edit: If you want to delete multiple iterations of a specific element, remove the break; in the if-logic. If you're only looking for the first, leave the break.

Solution 3:

Use This:

mates.removeChild(mates.children[i]);

Example: http://jsfiddle.net/t9nCT/1/

Solution 4:

You're retrieving a collection, so do,

parent[0].removeChild(mateToDelete);

Post a Comment for "Remove Element From Dom"