最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if an object is an instance of a NodeList in IE? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Sep 30, 2008 at 1:22 jon asked Sep 30, 2008 at 0:49 jonjon 9273 gold badges10 silver badges10 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 15

"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");
}

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");
}

I would just use something that always evaluates to a certain type. Then you just do a true/false type check to see if you got a valid object. In your case, I would get a reference to the select item like you are now, and then use its getOptions() method to get an HTMLCollection that represents the options. This object type is very similar to a NodeList, so you should have no problem working with it.

With jQuery:

if (1 < $(el).length) {
    alert("I'm a NodeList");
}
发布评论

评论列表(0)

  1. 暂无评论