Nehal Rupani
Nehal Rupani

Reputation: 21

How to change the div class as per content of that?

I want to change the class of the div if the length LI is greater than 3. and if less than 3 then class name should be the default like "content" and if more than 3 then class name should be "scroll-content"

    <div class="classname">

<ul>
 <li>Content</li>
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
</ul>
    </div>

i prefer using jQuery for this,

Upvotes: 1

Views: 422

Answers (3)

Doug Neiner
Doug Neiner

Reputation: 66191

It can be done with a single call and no conditionals

$('ul li:nth-child(4)')
   .closest('div')
   .removeClass('content')
   .addClass('scroll-content');

This assumes your default class is 'content' as you suggested.

This call finds any ul with at least 4 children (i.e. more than 3), it then finds the closest div that is a parent, and removes the default class and adds the scroll-content class.

Upvotes: 0

rahul
rahul

Reputation: 187030

$(function() {
    if ( $("div.classname > ul li" ).length > 3 )
    {
        $("div.classname").removeClass().addClass('anotherclass');
    }
    else if ( ...)
    {
        // add another class
    }
});

Upvotes: 0

cletus
cletus

Reputation: 625077

Try:

$("ul").each(function() {
  $(this).parents("div.classname:first")
    .addClass($(this).children().length > 3 ? "scroll-content" : "content");
});

or maybe something like:

$("div.classname").each(function() {
  $(this).addClass($(this).find("ul").children().length > 3 ? "scroll-content" : "content");
});

Upvotes: 3

Related Questions