I have on the page a certain number of elements with the same class. How to find out how many of them using js or jquery?

    4 answers 4





       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="div"></div> <div class="div"></div> <div class="div"></div> <div class="div"></div> 

        On jQuery, you can

         var count = $('.someClass').size(); alert(count); 
        • oh yes, given that size deprecated and in fact just returns length proof. - Specter
        • in the sense of? size crookedly working or what?) - Bob Marley
        • 9 times out of nine use .length - Specter
        • well ok)) I will use) - Bob Marley

        I have been doing this recently:

         var texts = document.querySelectorAll(".slider .subslider"), suball = texts.length; $('span').append(suball); 
         <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div class="slider"> <div class="subslider">0</div> </div> <div class="slider"> <div class="subslider">1</div> </div> <div class="slider"> <div class="subslider">2</div> <div class="subslider">3</div> <div class="subslider">4</div> </div> <span>Количество: </span> 

        In this case, if the elements are scattered throughout the page, and we must not just count them, but keep the order. I do this:

          var texts = document.querySelectorAll(".slider .subslider"), suball = texts.length, arrtext = Array.from(texts); $('span').append(suball); var i = 0; for(; i < suball; i++){ var co = i; $(arrtext[co]).append(co); } 
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div class="slider"> <div class="subslider">0 Suball: </div> </div> <div class="slider"> <div class="subslider">1 Suball: </div> </div> <div class="slider"> <div> <div class="subslider">2 Suball: </div> <div class="subslider">3 Suball: </div> </div> <div class="subslider">4 Suball: </div> </div> <span>Количество: </span> 

        On jQuery, I never found how to do it, only the set is inside one parent, the other is considered new. At least I came across this problem three years ago. I needed to count the total number of elements scattered around the page, and deduce their order ..... Yes, maybe I was stupid somewhere, or in everything, but I am only a JS user, and not a developer on it. And on pure - the easiest way that I found after so much time.