2014-01-22 22 views
0
var menuheader = document.createElement("li"); 
document.getElementsByClassName("subMenu").appendChild(menuheader); 

以上是代碼段。我得到這個錯誤:如何使用純javascript將具有指定類名的所有節點附加到子節點

firebug: TypeError: document.getElementsByClassName(...).appendChild is not a function 
+1

因爲'getElementsByClassName()'返回nodeList!嘗試使用'document.getElementsByClassName(...)[0] .appendChild'來定位列表中的第一個元素! –

+0

我建議在使用任何不熟悉的DOM方法之前閱讀MDN文檔。這是'getElementsByClassName'的一個:https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName –

回答

0

應該

var menuheader = document.createElement("li");// creates main menu to which below submenu should be added. 
var submenus=document.getElementsByClassName("subMenu"); //gives an array so you cannot append child to that. 

    for(int i=0;i<submenus.length;i++){ 
    menuheader.appendChild(submenus[i]); 

    } 

從你的代碼看起來你正在做相反的,它是將MainMenu的再次哪個子菜單。

document.createElement("li"); //create a main menu say Services 

服務

所以我需要子菜單添加到上面的元素,使其看起來應該像

服務

- >非收費服務

- > IT服務

- >可結算服務

+0

謝謝Shoaib多數民衆權納這是我在尋找一個「for循環」,因爲這種方法返回一個節點列表。 – Wandile

+0

如果它對你有幫助,你可以接受答案。謝謝 –

相關問題