2012-01-13 20 views
5

我有一個HTMLCollection對象,我可以用它來操作HTMLCollection的內容。我想知道如何將一個div元素添加到HTMLCollection的第一個,最後一個或任何特定索引。請提出建議。 這裏nDivs是HTML集合。如何將元素添加到JavaScript中的HTMLCollection?

var Div = document.createElement('div'); 
    for(i=0; i<9; i++){ 
     Div.appendChild(nDivs[0].children[0]); 
    } 
    Div.id = nDivs[0].id; 
    nDivs[0].parentNode.removeChild(nDivs[0]); 

    nDivs.appendChild(Div); //this is creating problem..need an alternative to this 
    document.getElementById("ABC").appendChild(nDivs[nDivs.length - 1]); 
+0

我已經嘗試了很多很多的方法...將集合轉換爲數組然後繼續,但這不符合我的目的。我能夠從該集合中刪除元素,但添加元素不會發生。 – Ruchir 2012-01-13 19:48:16

+0

也許在這裏複製一些代碼來設置你的HTMLCollection,並準確顯示你想要的內容 – cambraca 2012-01-13 19:49:08

+0

我建議在你的問題中包括一些代碼,並具體指出你的困難是什麼。 – paislee 2012-01-13 19:49:47

回答

9

按照MDN docs

HTMLCollection是表示 元件的一般集合(按文檔順序)的接口,並提供方法和屬性爲 遍歷列表。

由於它的接口,您只能通過它的methodsHTMLCollection進行交互。沒有方法可以修改對象,只能讀取它。 您必須以其他方式操作DOM

這裏有一些建議使用純JS,但我強烈建議jQuery這樣的任務。假設我們有一個新的元素newDivHTMLCollectiondocument.forms工作:

插入之前forms[1]

插入後 forms[1]
forms[1].parentNode.insertBefore(newDiv, forms[1]); 

// there is no insertAfter() so use the next sibling as reference element 
forms[1].parentNode.insertBefore(newDiv, forms[1].nextSibling); 

更換forms[1]

forms[1].parentNode.replaceChild(newDiv, forms[1]); 

文檔和示例insertBefore()replaceChild()nextSibling,並parentNode

+0

它適用於我..謝謝! – Ruchir 2012-01-13 20:57:59

相關問題