4

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

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

6 Comments

Firefox says it's a HTMLCollection, but according to the book "JavaScript: The Definitive Guide", by David Flanagan, it's a NodeList (page 767).
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 bug
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]) ??
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.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.