Javascript/jquery—在dom中向上两级(让我们称这个对象为“A”),然后将css应用于“A”的一个子对象;A「;

Javascript/jquery—在dom中向上两级(让我们称这个对象为“A”),然后将css应用于“A”的一个子对象;A「;,javascript,jquery,css,Javascript,Jquery,Css,我没有找到解决这个问题的办法 $(.child”).最近的(“父母”).最近的(“祖父母”) 当我有了这个对象,我想对它的一个孩子应用一些css(让我们称之为我的教父) 非常感谢你的帮助 .grandparent.mygodfather{ background-color: red }``` 可用于选择“教父”元素: 演示: $(.child”).closest(.祖父母”).find(.goddaver').css('background-color','red') div{ 边框:1px

我没有找到解决这个问题的办法

$(.child”).最近的(“父母”).最近的(“祖父母”)

当我有了这个对象,我想对它的一个孩子应用一些css(让我们称之为我的教父)

非常感谢你的帮助

.grandparent.mygodfather{
background-color: red
}```
可用于选择“教父”元素:

演示:

$(.child”).closest(.祖父母”).find(.goddaver').css('background-color','red')
div{
边框:1px实心#ccc;
保证金:1雷姆3雷姆;
}

祖父母
父母亲
小孩
教父
您可以使用向上遍历DOM树(在您的示例中是获取“parent”和“祖父母”),然后使用或选择正确的子元素(在您的示例中是“mygoddaver”)

由此产生的代码将是:

$(".child").parent().parent().next(".mygodfather");

为什么不能直接使用
$(“.child”).closest(“.祖父母”)
$(".child").parent().parent().next(".mygodfather");