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 文档时,该方法对大小写不敏感。
非数组
两者都类数组,但非数组,于是不能使用Array的方法,但可把两者先转换为数组。
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更方便。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。