The Gmo
The Gmo

Reputation: 274

Adding a class to an ul that has more (or) less than 2 li's

I'm trying to add a class to every ul that has more (or equal&less than) 2 li's.

Somehow I can't get it going. I either end up with a class added to all level 2 ul's or to none.

Here's the code I'm, using:

$(document).ready(function() {
  var countli = $('ul.level_2 li').length;
    if(countli >= 3) {
      $("ul.level_2").addClass("short");
    }
});

What am I missing?

http://jsfiddle.net/gmodesignz/20dksk4y/3/

Upvotes: 1

Views: 1359

Answers (4)

Osama Mohamed
Osama Mohamed

Reputation: 697

$(document).ready(function() {
    $("ul .level_2").each(function(){
        var countLi = $(this).find("li").length;
        if(countLi <= 3 ){
           $(this).find("li").addClass("short");
         }
    });
});

http://jsfiddle.net/OsamaMohamed/wsu8xwwg/

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You should use .filter()

Reduce the set of matched elements to those that match the selector or pass the function's test.

Script

$("ul.level_2").filter(function () {
    return $(this).find('li').length >= 3
}).addClass("short");

DEMO

Upvotes: 7

Arun P Johny
Arun P Johny

Reputation: 388316

You can add the class to ul elements which has a 3rd li child(ie has more than 2 li) like

$(document).ready(function() {
  $('ul.level_2').has('li:eq(2)').addClass("short");
});
ul {
  color: blue;
}
.short {
  color: red;
}
.large {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>No Submenu</li>
  <li class="sub">
    Long Submenu
    <ul class="level_2">
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
    </ul>
  </li>
  <li class="sub">
    Short Submenu
    <ul class="level_2">
      <li>Something</li>
      <li>Something</li>
    </ul>
  </li>
</ul>

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

What you are doing is you are generalizing everything. Make it specific inside the closures. See the below snippet:

$(document).ready(function() {
  $('ul.level_2').each(function () {
    if ($(this).children().length > 2)
      $(this).addClass("short");
  });
});
* {font-family: 'Segoe UI';}
ul {color: blue;}
.short {color: red;}
.large {color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
  <li>No Submenu</li>
  <li class="sub">
    Long Submenu
    <ul class="level_2">
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
      <li>Something</li>
    </ul>
  </li>
  <li class="sub">
    Short Submenu
    <ul class="level_2">
      <li>Something</li>
      <li>Something</li>
    </ul>
  </li>
</ul>

Also you must apply the class to the parents and not the children.

Upvotes: 2

Related Questions