仅在第一个li内查找h2

Find h2 within first li only

本文关键字:查找 h2 li 第一个      更新时间:2023-09-26

我希望jquery在旋转木马的第一个li中针对一个h2,然后我将向其添加一些css。

作为一个基本的例子,到目前为止我有这个

$('li').first().css('background-color', 'red');

这只是针对li。然后我该如何针对h2应用css?它会使用.find属性吗?

我知道我可以在CSS中做到这一点,但我想在jquery中做到,因为它在jquery中将添加其他功能。

"它会使用.find属性吗?"

是的,find()方法(不是属性)是一种方法:

// all h2 elements within the first li:
$('li').first().find('h2').css('background-color', 'red');
// or just the first h2 within the first li:
$('li').first().find('h2').first().css('background-color', 'red');

或者您可以尝试如果h2在DOM中比li:低一级

// all h2 elements within the first li:
$('li').first().children('h2').css('background-color', 'red');

因为find()是多级的,这会使它变慢。

.children()方法与.find()方法的不同之处在于,.childred()只在DOM树中向下移动一个级别,而.find)也可以向下遍历多个级别来选择子元素(孙元素等)。此处记录

试试这个:

$('li:first h2').css('background-color', 'red');