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

2023-11-30

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]);

  }

从您的代码看来,您正在做相反的事情,即再次将主菜单添加到子菜单中。

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

Services

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

Services

->非计费服务

->IT服务

->计费服务

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用纯 javascript 将子级附加到具有指定类名的所有节点 的相关文章

随机推荐