How to detect HTMLCollection/NodeList in JavaScript?

前端 未结 7 526
刺人心
刺人心 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:44

    script:

    Element.prototype.isNodeList = function() {return false;}
    NodeList.prototype.isNodeList = HTMLCollection.prototype.isNodeList = function(){return true;}
    

    use like this:

    var d; // HTMLCollection|NodeList|Element
    if(d.isNodeList()){
      /*
        it is HTMLCollection or NodeList
        write your code here
      */
    }else{
      /*
        it is not HTMLCollection and NodeList
        write your code here
      */
    }
    
    0 讨论(0)
提交回复
热议问题