I am trying to remove certain values from an array containing input fields in a form:
allFields = theForm.getElementsByTagName("INPUT");
for(j = 0; j < allFields.length; j++) {
if(allFields[j].className == "btn" || allFields[j].className == "lnk") {
allFields.splice(j,1);
}
}
It causes an error. Firebug shows following error and the script doesn't work.
allFields.splice is not a function
This also happened with any other Array method I tried. How can I fix this?
Mohammad Usman
39.5k20 gold badges99 silver badges101 bronze badges
asked Aug 26, 2010 at 11:51
Dean
8,1259 gold badges32 silver badges32 bronze badges
1 Answer 1
allFields is not an array, but a NodeList.
If you want to remove elements, do a reverse loop and use removeChild:
var allFields = theForm.getElementsByTagName("input");
for(var j=allFields.length-1; j>=0; j--){
if(allFields[j].className == "btn" || allFields[j].className == "lnk"){
allFields[j].parentNode.removeChild(allFields[j]);
}
}
Nikhil
5,8091 gold badge34 silver badges31 bronze badges
answered Aug 26, 2010 at 11:52
Lekensteyn
67k25 gold badges169 silver badges205 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
Lekensteyn
Firefox says it's a HTMLCollection, but according to the book "JavaScript: The Definitive Guide", by David Flanagan, it's a NodeList (page 767).
Gumbo
getElementsByTagName returns a NodeList.Lekensteyn
Well, that's a bug in Firefox then.
document.getElementsByTagName('a') instanceof NodeList evaluates to true in Chrome, but Firefox says false. edit: yes it's a bugDean
Thanks, I didn't know that. Why does it have to be a reverse loop? Is it possible to remove child with allFields.removeChild(allFields[j]) ??
Lekensteyn
If you remove a node, the loop will skip the next node. That's because the NodeList is dynamic. This story applies to arrays too.
|
lang-js