Count elements on the screen

8

I would like to know if there is a possibility that I can count the elements on the screen, for example a function that lists the amount of <li> on my webpage.

How could I do this? And how would function work?

    
asked by anonymous 01.12.2015 / 14:54

7 answers

9

You can do it like this:

function contar(what){
   return document.querySelectorAll(what).length; 
}

For example in this page using contar('li') gives 92. With this function you can pass a CSS selector as ul li.nome which also works.

Example: link

    
01.12.2015 / 14:58
4

With pure javascript you can do this:

document.querySelectorAll('li').length

length will return the number of items in your document.

    
01.12.2015 / 14:58
4

You can use JQuery to do this, for example

$('li').size();

You can also put a class in li type <li class="item"> and use

$('.item').size();

So you do not run the risk of catching all the li's on the page.

    
01.12.2015 / 14:58
3

In this way it is possible, the script will scan all elements li .

@Edit: Simplified form.

var elementos = document.getElementsByTagName('li');
document.writeln('Existem ' + elementos.length);
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

@Edit: implementation of count.

var elementos = document.getElementsByTagName('li');
var count = 0;
Array.prototype.forEach.call(elementos, function(arr) {
  console.log(arr);
  count++;
});
document.writeln('Existem ' + count);
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
    
01.12.2015 / 14:59
3

Your best solution will undoubtedly be with .length and as it is such a simple thing nor do you have the need for jquery .

I would only change one question, the selector, in some tests in browsers document.getElementsByTagName is faster than document.querySelectorAll .

getElementsByTagName vs querySelectorAll

So if you get all the elements read and tell and your problem would look something like this:

var li = document.getElementsByTagName('li').length;
document.write('Quantidade de li: ' + li);
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
</ul>

<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
  <li>F</li>
</ul>
    
01.12.2015 / 16:40
3

Make it easy, do so

$('li').length

Ready, simple, easy and clean

    
01.12.2015 / 16:20
-1

Try this with Jquery:

 var i = 0;
 $('li').each(function(){
     i++                         
 });
 alert(i);
    
01.12.2015 / 14:57