Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is an instance of a NodeList in IE?

Tags:

javascript

Why is NodeList undefined in IE6/7?

<form action="/" method="post" id="testform">
    <input type="checkbox" name="foobar[]" value="1" id="" />
    <input type="checkbox" name="foobar[]" value="2" id="" />
    <input type="checkbox" name="foobar[]" value="3" id="" />    
</form>

<script type="text/javascript" charset="utf-8">
(function () {
    var el = document.getElementById('testform')['foobar[]']
    if (el instanceof NodeList) {
        alert("I'm a NodeList");
    }  
})();
</script>

This works in FF3/Safari 3.1 but doesn't work in IE6/7. Anyone have any ideas how to check if el is an instance of NodeList across all browsers?

like image 366
jon Avatar asked Sep 30 '08 00:09

jon


2 Answers

"Duck Typing" should always work:

...

if (typeof el.length == 'number' 
    && typeof el.item == 'function'
    && typeof el.nextNode == 'function'
    && typeof el.reset == 'function')
{
    alert("I'm a NodeList");
}
like image 191
Adam Franco Avatar answered Sep 22 '22 15:09

Adam Franco


Adam Franco's answer almost works. Unfortunately, typeof el.item returns different things in different version of IE (7: string, 8: object, 9: function). So I am using his code, but I changed the line to typeof el.item !== "undefined" and changed == to === throughout.

if (typeof el.length === 'number' 
    && typeof el.item !== 'undefined'
    && typeof el.nextNode === 'function'
    && typeof el.reset === 'function')
{
    alert("I'm a NodeList");
}
like image 36
craigpatik Avatar answered Sep 20 '22 15:09

craigpatik