javascript - 如何将类添加到div的父子

标签 javascript jquery html css

<div class="parent">
  <div class="child-class">
    <div>
      <div class="child-class">
        <div>
          <div class="child-class">
            <div>
            </div>

我需要使用 jQuery 添加一个类到第二个 child-class

最佳答案

通过 CSS 选择器寻址父级的第二个子级:

$('.parent > .child-class:nth-of-type(2)').addClass('your-class');

使用 nth-of-type 而不是 nth-child 的优势在于可以更精确地选择您想要的内容。 nth-child 将选择您 parent 的任何 child 。 nth-of-type 只会选择特定类型的 child (在本例中为 class child-class)。

关于javascript - 如何将类添加到div的父子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47754681/

相关文章:

html - 影响导航栏对齐的图像

javascript - 更改类的 html 不起作用

javascript - socket.io - 无法从服务器向特定客户端发送数据

php - 立即加载 URL 导航

javascript - 为什么当我分配变量时控制台打印未定义?

javascript - "$.getJSON is not a function"使用 babel-node 和 ES6 中的 jQuery

javascript - 如何在特定 DIV 的 DOM 中更早地激活 JavaScript?

javascript - jQuery - 在 .css() 方法中组合变量和字符串

php - jquery-输出始终仅在第一项中

javascript - 如何防止任何 iframe 或任何其他脚本更改顶部窗口中文档的标题?