views:

37

answers:

1

Hi, 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 "allFields.splice is not a function" error, and the script doesn't work.

This also happened with any other Array method I tried :(

Thanks in advance

+3  A: 

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; j>=0; j--){
    if(allFields[j].className == "btn" || allFields[j].className == "lnk"){
        allFields[j].parentNode.removeChild(allFields[j]);
    }
}
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).
Lekensteyn
[`getElementsByTagName`](http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-getElementsByTagName) returns a [`NodeList`](http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-536297177).
Gumbo
Well, that's a [bug in Firefox](https://bugzilla.mozilla.org/show_bug.cgi?id=14869) then. `document.getElementsByTagName('a') instanceof NodeList` evaluates to `true` in Chrome, but Firefox says `false`. *edit: yes it's a bug*
Lekensteyn
It's not a bug as per the DOM standard. `HTMLCollection` correctly implements the `NodeList` interface. DOM doesn't say anything about concrete classes or `instanceof` having to match anything, it only requires that the described methods be present on the return objects. You can't even be sure that a `NodeList` constructor function will be present as a `window` property or that testing against it is meaningful.
bobince
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]) ??
Dean
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.
Lekensteyn