Berre Posted February 12, 2012 Share Posted February 12, 2012 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 } Quote Link to comment https://forums.phpfreaks.com/topic/256928-removechild-not-working-properly/ Share on other sites More sharing options...
requinix Posted February 12, 2012 Share Posted February 12, 2012 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. } Quote Link to comment https://forums.phpfreaks.com/topic/256928-removechild-not-working-properly/#findComment-1317166 Share on other sites More sharing options...
Berre Posted February 12, 2012 Author Share Posted February 12, 2012 Thanks for both explaining and showing. That solved it Quote Link to comment https://forums.phpfreaks.com/topic/256928-removechild-not-working-properly/#findComment-1317168 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.