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更方便。對象

相關文章
相關標籤/搜索