You are very close! You want to add a directive to only grab direct descendants: ">"
$('div.wrap').find('> p:not(.no):first').addClass('red');
题
I want to create a script which will add a class to the first child without a specific class, for each parent with a specifice class. For example:
<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>
My javascript is as follows:
$('div.wrap').find('p:not(.no):first').addClass('red');
This will select descendent without class="no"
, as opposed to the first child (so item 2, as opposed to item 3 in the above example).
I've tried changing .find
to .children
, but then it only selects the first example on the page, not the first in each set (so only item 2 in the above example, not item 6).
Here is a codepen illustrating the above http://cdpn.io/izGDH
解决方案
You are very close! You want to add a directive to only grab direct descendants: ">"
$('div.wrap').find('> p:not(.no):first').addClass('red');
其他提示
This is one way:
$('div.wrap p.no').each(function(){ $(this).siblings('p').first().addClass('red'); })