Jump to content

removeChild() not working properly


Berre

Recommended Posts

I was writing a script that seemed to work flawlessly, but when I tried it on my girlfriends laptop it didn't work. Other JavaScript code worked so it's not disabled, but not this particular script. Both computers (mine and hers) run Firefox 10 (not 100% sure if she has version 9 or 10 though) on Windows 7. It's very early in the process, so I haven't tested it very much in different browsers etc. I just tried it in Chrome on my computer, and it doesn't work there either.

 

Below is the snippet of code that fails. The purpose is to remove all elements with the class name details.

 

var details = document.getElementsByClassName("details");

for (var i in details) {
   var p = details[i].parentNode;
   p.removeChild(details[i]);      // This line fails
}

Link to comment
https://forums.phpfreaks.com/topic/256928-removechild-not-working-properly/
Share on other sites

There are two problems:

 

1. getElementsByClassName (as well as getElementsByTagName) returns a DOMNodeList, or whatever the name of the interface is. It's more than just an array: it can change as its elements change. When you remove items that are found in that list, they also disappear from the list. As i counts up, the length of the list counts down.

2. "in" is dangerous. It will find everything that's a member of whatever you're trying to traverse. Try console.log()ing or alert()ing i, see what you get.

 

var details = document.getElementsByClassName("details");

// simply going from 0->length wouldn't work as the length changes
// going in reverse is a cheap alternative
for (var i = details.length; i > 0; i--) {
var p = details[0].parentNode;
p.removeChild(details[0]); // once removed, [1] becomes [0], [2] becomes [1], etc.
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.