How to detect HTMLCollection/NodeList in JavaScript?

前端 未结 7 525
刺人心
刺人心 2020-12-05 02:55

I\'m not sure my current implementation is available all the time:

function isNodeList(nodes) {
    var result = Object.prototype.toString.call(nodes);
    /         


        
相关标签:
7条回答
  • 2020-12-05 03:17

    The following should return true, if nodes is of type NodeList

    NodeList.prototype.isPrototypeOf(nodes)
    

    @DavidSpector, for HTMLCollection you can similarly use :

    HTMLCollection.prototype.isPrototypeOf(collection)
    
    0 讨论(0)
  • 2020-12-05 03:29

    This answer is probably really really late, but....

    if (nodes == '[object NodeList]') {
      // It's a nodeList
    }
    
    0 讨论(0)
  • 2020-12-05 03:32

    Here is how to test if an object is a NodeList in modern browsers:

    if (nodes instanceof NodeList) {
      // It's a NodeList object
    }
    
    0 讨论(0)
  • 2020-12-05 03:37

    Check if variable is an HTMLcollection or a dom element

      var foo = document.getElementById('mydiv');
      var foo2 = document.getElementsByClassName('divCollection');
      console.log(foo instanceof HTMLElement);
      console.log(foo instanceof HTMLCollection);
    
    0 讨论(0)
  • 2020-12-05 03:37

    I created a benchmark of all answers here to see, what is the best approve in speed. Turns out NodeList.prototype.isPrototypeOf(nodes) is by far the fastest. But in a normal use-case nodes instanceof NodeList would be fine too.

    I personally would just not pick the isNodeList function, because its slow, custom and too much overhead.

    0 讨论(0)
  • 2020-12-05 03:43

    I would structure the code differently:

    function isNodeList(nodes) {
        var stringRepr = Object.prototype.toString.call(nodes);
    
        return typeof nodes === 'object' &&
            /^\[object (HTMLCollection|NodeList|Object)\]$/.test(stringRepr) &&
            (typeof nodes.length === 'number') &&
            (nodes.length === 0 || (typeof nodes[0] === "object" && nodes[0].nodeType > 0));
    }
    

    Notes:

    • less return paths make easier-to-read code
    • stick with one type of logic, if possible (i.e. use less negated checks)
    • "item" is not mandatorily in a nodeList
    • use hasOwnProperty() instead of in
    • use square brackets to index into the list
    • I don't think a try/catch is really necessary, but that might be wrong - you decide
    • check for nodeType instead of tagName, as text nodes or comments do not have a name
    • add more checks to the && chain if you see fit
    0 讨论(0)
提交回复
热议问题