How to find number of
    inside each div

后端 未结 4 1560
广开言路
广开言路 2021-01-24 03:49

I have a large file of this form [similar div\'s throughout]. I want to be able to select a div, find the number of ul\'s in it and traverse through ea

4条回答
  •  独厮守ぢ
    2021-01-24 04:14

    First of all you need to work out the correct selector for each DIV.

    The selector you want is:

    ".experiment"
    

    Notice the . to denote a class selector.

    This will allow you access to each DIV element. If you then want to loop though each of these, you can do so like this:

    $(".experiment").each(function(){
       var div = $(this);
    
       var elementsInThisDiv = div.find("ul");
       //you now have a list of all UL elements in the current DIV only
    
       var numberOfElements = elementsInThisDiv.length;
       //you now have a count of UL elements belonging to this DIV only
    
       //you can loop the UL elements here
       $(elementsInThisDiv).each(function(){
           var ul = $(this);
           //do something with the UL element
    
           //like get the LI elements...
           var liElements = ul.find("li");
       });
    });
    

    IMPORTANT: There is also an error with your HTML, you need to close your

      elements correctly using

提交回复
热议问题