Moose
Moose

Reputation: 1241

jQuery - Check to see if all siblings have the same class, if so do something

I'm writing a jquery function to check and see if all the sibling li's have a certain class of "out", if so then do something. I can't figure out where I'm going wrong. Any help would be greatly appreciated!

My failed Codepen attempt

<ul>
  <h3>I'm a title</h3>
  <li class="out">Item 1</li>
  <li class="">Item 2</li>
  <li class="">Item 3</li>
</ul>

<ul>
  <h3>I'm a second set of people</h3>
  <li class="out">Item 1</li>
  <li class="out">Item 2</li>
  <li class="out">Item 3</li>
</ul>

$('h3').each(function() {
  if( $('h3').nextAll('li').hasClass('out')) {
    $('h3').css('background', 'red');
  }
});

Upvotes: 0

Views: 1817

Answers (2)

Satpal
Satpal

Reputation: 133403

Yours is invalid HTML, so changed it to

HTML

<h3>I'm a title</h3>
<ul>
    <li class="out">Item 1</li>
    <li class="">Item 2</li>
    <li class="">Item 3</li>
</ul>
 <h3>I'm a second set of people</h3>
<ul>
    <li class="out">Item 1</li>
    <li class="out">Item 2</li>
    <li class="out">Item 3</li>
</ul>

JavaScript

$('ul').each(function() {
  if( $(this).find('li.out').length == $(this).find('li').length) {
    $(this).prev('h3').css('background', 'red');
  }
});

DEMO

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

html

<ul>
  <li><h3>I'm a title</h3></li>
  <li class="out">Item 1</li>
  <li class="">Item 2</li>
  <li class="">Item 3</li>
</ul>

<ul>
  <li><h3>I'm a second set of people</h3></li>
  <li class="out">Item 1</li>
  <li class="out">Item 2</li>
  <li class="out">Item 3</li>
</ul>

then

$('li:has(h3)').each(function() {
  if($(this).siblings(':not(.out)').length == 0){
    $(this).find('h3').css('background', 'red');
  }
});

Demo: Fiddle

Upvotes: 2

Related Questions