Select first immediate child without a specific class, for each parent with a specific class using jquery

StackOverflow https://stackoverflow.com/questions/23436422

  •  14-07-2023
  •  | 
  •  

Question

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

Was it helpful?

Solution

You are very close! You want to add a directive to only grab direct descendants: ">"

$('div.wrap').find('> p:not(.no):first').addClass('red');

http://jsfiddle.net/wnewby/HUqR9/

OTHER TIPS

This is one way:

$('div.wrap p.no').each(function(){ $(this).siblings('p').first().addClass('red'); })

jsFiddle example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top