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
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.
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.