Jquery: if children with a specific class?

I wonder how I can determine if 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>'); } 

???

+6
jquery
source share
3 answers
 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/

+8
source share
 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:

  • Ul has more than two li elements,
  • There is at least one li with section-title class
  • There is at least one li with an active class
+1
source share
 var ul = $('#ul_id'); if ($('.class1, .class2', ul).size()>2) 

you do not need to check the first condition (has more than two children), since this is an AND condition, and if your second condition satisfies, the first condition is trivial.

James lin

guanfenglin@gmail.com

0
source share

All Articles