繁体   English   中英

如何使用纯JavaScript将子级附加到具有指定类名的所有节点上

[英]How do I append a child to all the nodes with the specified classname using pure javascript

var menuheader = document.createElement("li"); 
document.getElementsByClassName("subMenu").appendChild(menuheader);

上面是代码片段。 我收到此错误:

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

它应该是

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添加到submenu。

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

服务

所以我需要在上面的元素上添加子菜单,以便它看起来像

服务

->非收费服务

-> IT服务

->计费服务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM