开发者

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

开发者 https://www.devze.com 2022-12-11 20:46 出处:网络
I want to change the class of the div if the lengthLI 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 s

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,


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");
});


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消