Javascript – How to change the div class as per content of that

csshtmljavascriptjquery

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,

Best Solution

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