Add Class to <body> if a DIV has more then 4 elements

做~自己de王妃 提交于 2019-12-14 03:34:19

问题


I'm trying to add class to <body> when <div class="scroll"> has more then 4 <li>text</li> elements.

HTML:

 <body>  
   <div class="scroll">
   <div>   <!-- Parent Element -->
     <ul>    <!-- Parent Element 2 -->
     <li>text</li>     <!-- Child 1-->
     <li>text</li>     <!-- Child 2-->
     <li>text</li>     <!-- Child 3-->
     <li>text</li>     <!-- Child 4-->
     <li>text</li>     <!-- Child 5-->
     </ul>
   </div>
   </div>
 <body>

Means if <div class="scroll"> has 5 <li>text</li> item then add class to body like <body class"popup">. Any body know how to do this by Jquery. Thanks in advance.


回答1:


You can use setInterval (only needed if your li's are added removed dynamically, you may skip it if it's not the case), and check it's length inside and do respective action as needed.

setInterval(function(){
    if(jQuery('div.scroll ul > li').length > 4)
        jQuery('body').addClass('popup');
    else
        jQuery('body').removeClass('popup');
}, 1000);

Note: You need to place this script before closing of body tag or after of elements for which length needs to be compared.




回答2:


I think you're after something like the following.

$(function() {
    //Will execute as soon as the DOM is loaded
    addBodyClass();

    //Let's say a click function somewhere deletes a LI
    $("selector").on("click", function() {
        $('.scroll li:last').remove();
        //Now there are 4 LIs which means remove the popup class from body
        //So, call the function again
        addBodyClass();
    });

});

function addBodyClass() {

    $('.scroll li').length > 4 && $("body").addClass("popup") || $("body").removeClass("popup");

    //The above is the shorter version of
    if ($('.scroll li').length > 4) {
        $("body").addClass("popup");
    } else {
        $("body").removeClass("popup");
    }
}



回答3:


This should Work for you

<script type="text/javascript">

   $(document).ready(function(){

   if ($('.scroll li').length > 4) {
     $("body").addClass("popup");
    } else {
     $("body").removeClass("popup");
   }

 });


</script>


来源:https://stackoverflow.com/questions/31635213/add-class-to-body-if-a-div-has-more-then-4-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!