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

后端 未结 4 870
心在旅途
心在旅途 2020-12-31 20:19

Why is NodeList undefined in IE6/7?

相关标签:
4条回答
  • 2020-12-31 20:42

    "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");
    }
    
    0 讨论(0)
  • 2020-12-31 20:44

    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.

    0 讨论(0)
  • 2020-12-31 20:48

    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");
    }
    
    0 讨论(0)
  • 2020-12-31 20:49

    With jQuery:

    if (1 < $(el).length) {
        alert("I'm a NodeList");
    }
    
    0 讨论(0)
提交回复
热议问题