DOM疑惑点整理(一)

Nodelist和HTMLCollection

定义区别

Nodelist是多种类型节点的集合,HTMLCollection是元素类型节点的集合。数组

API区别

返回Nodelist的API:Node.childNodes 和 document.querySelectorAll
返回HTMLCollection的API:
Node.children、
document.getElementsByTagName、
document.getElementsByTagNameNS、
document.getElementsByClassName函数

属性、方法区别

二者共有:
length: NodeList 对象中包含的节点个数.
item (id):返回NodeList对象中指定索引的节点,若是索引越界,则返回null.
HTMLCollection特有方法:
namedItem(name): 若是文档是 HTML 文档,该方法会首先查询带有匹配给定名称的 id 属性的节点,若是不存在匹配的 id 属性,则查询带有匹配给定名称的 name 属性的节点。当查询 HTML 文档时,该方法对大小写不敏感。prototype

非数组

二者都类数组,但非数组,因而不能使用Array的方法,但可把二者先转换为数组。code

function convertToArray(args){
        var array = null;
        try{
            array = Array.prototype.slice.call(args); 
            //ES6能够以下写
            //array = Array.from(args);
        }catch(ex){                             
            array = new Array();                   //针对IE8以前
            for(var i=0,len=args.length;i<len;i++){
                array.push(args[i]);
            }
        }
    }

getAttribute

通常利用getAttribute访问元素的style和onclick属性都会返回字符串类型的相应代码。
可是在IE7及以前版本用getAttribute访问style返回一个对象,访问onclick返回函数。
IE7及以前版本,用setAttribute设置style属性,不会有任何效果。
不建议用getAttributeNode、setAttributeNode,使用getAttribute、setAttribute和removeAttribute更方便。对象