Javascript 如何使用JS将类添加到子元素

Javascript 如何使用JS将类添加到子元素,javascript,css,dropdown,megamenu,Javascript,Css,Dropdown,Megamenu,我有一个导航菜单。我想将一个类作为.container添加到标记中,但仅当该元素具有类“megamenu”时。我怎样才能做到呢?因为我只有一个下拉菜单作为“超级菜单” 提前感谢。如果您想使用纯Javascript,可以使用className,请尝试下面的代码,否则使用jQuery也可以轻松做到这一点 //lets find the element with that class. var menu = document.querySelectorAll('.megamenu'); // l

我有一个导航菜单。我想将一个类作为.container添加到
标记中,但仅当该元素具有类“megamenu”时。我怎样才能做到呢?因为我只有一个下拉菜单作为“超级菜单”


提前感谢。

如果您想使用纯Javascript,可以使用
className
,请尝试下面的代码,否则使用jQuery也可以轻松做到这一点

//lets find the element with that class.
var menu = document.querySelectorAll('.megamenu');  

// lets verify only one menu with '.megamenu'
if(menu.length == 1)
{
  //set the class
  menu[0].className = " " + "anotherClassName";
}
更新

我们需要将该类应用于
megamenu

// lets verify only one menu with '.megamenu'
if(menu.length == 1)
{
  // set the class to the child '.container'
  // I'm expecting only one '.container' inside megamenu
  // if you have multiple and want apply for all use .querySelectorAll
  menu[0].querySelector('.container').className = " " + "anotherClassName";
}

当您想使用纯Javascript时,可以使用
className
,请尝试下面的代码,否则使用jQuery也可以很容易地做到这一点

//lets find the element with that class.
var menu = document.querySelectorAll('.megamenu');  

// lets verify only one menu with '.megamenu'
if(menu.length == 1)
{
  //set the class
  menu[0].className = " " + "anotherClassName";
}
更新

我们需要将该类应用于
megamenu

// lets verify only one menu with '.megamenu'
if(menu.length == 1)
{
  // set the class to the child '.container'
  // I'm expecting only one '.container' inside megamenu
  // if you have multiple and want apply for all use .querySelectorAll
  menu[0].querySelector('.container').className = " " + "anotherClassName";
}

var elements=document.querySelectorAll(“.megamenu下拉菜单”)。现在在它们上面循环并向它们添加类
var elements=document.querySelectorAll(“.megamenu dropdown”)。现在,在它们上面循环并添加类。感谢您的回复。它几乎可以工作,但并不完全如我所愿。查看HTML菜单项1的结构>
  • 菜单项1
  • 菜单项1
    • 菜单项3
    • ,因此您可以在
      下看到。megamenu
      .container
      这是我想要添加到的地方,如果在类megamenu上面,抱歉,响应有点混乱,您的意思是要将类添加到
      .container
      中,该容器是
      .megamenu
      的子级??这也很容易,np,我会更新答案,如果它能解决你的问题,别忘了把它标记为一个答案,这样对其他用户也会有帮助。谢谢你的回复。它几乎可以工作,但并不完全如我所愿。查看HTML菜单项1的结构>
    • 菜单项1
    • 菜单项1
      • 菜单项3
      • ,因此您可以在
        下看到。megamenu
        .container
        这是我想要添加到的地方,如果在类megamenu上面,抱歉,响应有点混乱,您的意思是要将类添加到
        .container
        中,该容器是
        .megamenu
        的子级??这也很简单,np,我会更新答案,如果它能解决你的问题,别忘了把它标记为答案,这样对其他用户也会有帮助。。