matt
matt

Reputation: 44413

jquery: if children with specific class?

i wonder how i can determine if a ul has MORE than 2 children and if there are two children with two specific classes inside this ul …

if($(this).children().length > 2 && $(this).children('.section-title, .active')) {
    $(this).append('<li class="dots">&hellip;</li>');
}

???

Upvotes: 6

Views: 14065

Answers (3)

James Lin
James Lin

Reputation: 26608

var ul = $('#ul_id');
if ($('.class1, .class2', ul).size()>2)

you don't need to test the first condition (has more than 2 children), since it's an "AND" condition, and if your second condition satisfies, the first condition is trivial.

James Lin

[email protected]

Upvotes: 0

spinon
spinon

Reputation: 10857

var ulChildren = $("li", this);
if (ulChildren.length > 2 && $('li.section-title', ulChildren).length >= 1 && $('li.active', ulChildren).length >= 1)

This will check the following rules:

  1. There are more than two li elements under the ul
  2. There is at least one li with the class of section-title
  3. There is at least one li with the class of active

Upvotes: 1

karim79
karim79

Reputation: 342775

var $ul = $('ul');
if($ul.find("li").length > 2 && $ul.find('.active, .inactive').length  == 2) {
       alert('yes, it is this way');
}​

<ul>
  <li class="active">Whatever</li>
  <li class="inactive">Whatever</li>
  <li>Whatever</li>
  <li>Whatever</li>
</ul>​

Demo: http://jsfiddle.net/RtTSM/1/

Upvotes: 8

Related Questions