How to find number of
    inside each div

后端 未结 4 1482
广开言路
广开言路 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:07

    Your HTML is currently incorrect, since you're simply starting new

    and
      elements rather than closing the existing ones. Ignoring that because it's trivial to fix, we'll move on to the real issue.

      You need to select all of the

      elements, then iterate through them. To do that you can use the .each() function. It might look something like this:

      var experiments = $('.experiment'); // all of them
      
      experiments.each(function(i, val) { // will iterate over that list, one at a time
          var experiment = $(this); // this will be the specific div for this iteration
          console.log("Experiment: " + experiment.find('.experiment-number').text());
          // outputs the experiment number
          console.log("Experiment ULs: " + experiment.find('ul').length);
          // number of 
        elements in this
        var total = 0; experiment.find('ul.data-values li').each(function() { total += parseInt($(this).text(), 10); }); console.log("Experiment total: " + total); // outputs the total of the
      • elements text values });

      Take a look at this jsFiddle demo.

    提交回复
    热议问题