如何使用 jquery 更改单个子元素的 class

How to change class of a single child element with jquery

我正在尝试这样做:

$(".expand")[0].children[0].addClass("test");

没用。

这个

$(".expand").get(0).children[0];

returns:

<i class=​"fa fa-chevron-circle-down">​::before​</i>​

我想更改它的 class。如何操作?

谢谢

根据选择器,您似乎正在尝试将 class 添加到具有 class 扩展的第一个元素中的第一个子元素。你可以使用:

$(".expand:first > *:first").addClass("test");

查看您的问题,您正在尝试将 class 添加到 class expand.Why 的第一个元素中,您是否为此目的使用 :first-child 选择器 $(".expand" tag:first-child)

为什么您的尝试无效:

  1. 在第一个中,您已将 jquery 对象转换为 dom 元素,并且您正在尝试应用 jquery .addClass() 方法。所以这会导致错误。
  2. 在第二个中,您使用了 .get(0),它也为您提供了 dom 节点而不是 jquery 对象。所以这也会导致错误。

解决方案:

$(".expand:eq(0) > *:eq(0)").addClass("newClass");

此行将为您提供 class expand 的第一个元素,它会找到第一个子元素,然后应用新的 class。

尽管您也可以使用纯 js 来做到这一点:

var parent = document.getElementsByClassName('expand')[0];
    parent.children[0].className = "newClass";