我想创建一个脚本,它将为没有特定类的第一个孩子添加一个类,对于每个具有特定类的父代。 例如:选择没有特定类的第一个直接孩子,对于每个使用jquery的具有特定类的父类
<div class="wrap">
<p class="no">1. Not this one please</p>
<div>
<p>2. not this either</p>
</div>
<p>3. Make this red!</p>
<p>4. Not this</p>
</div>
<div class="wrap">
<p class="no">5. Not this one please</p>
<p>6. Make this red also!</p>
<p>7. Not this</p>
</div>
我的JavaScript如下:
$('div.wrap').find('p:not(.no):first').addClass('red');
这将选择的后代不class="no"
,相对于所述第一子(这样的项目2中,如在上述的相对第3项例)。 我试过将.find
更改为.children
,但它只选择页面上的第一个示例,而不是每个集合中的第一个示例(因此仅上面示例中的第2项,而不是第6项)。
这里是一个codepen表示在上述http://cdpn.io/izGDH