How to count the elements of a li in jquery

1

You can count the elements that are inside the li, but that is by step, for example first take the li1 and count the elements that in the case has to return 3 and then move on to another li.

<ul>
   <li id='li1'>
     <a>elemento 1</a>
     <a>elemento 2</a>
     <a>elemento 3</a>
   </li>
   <li id='li2'>
     <a>elemento 1</a>
     <a>elemento 2</a>
     <a>elemento 3</a>
   </li>
</ul>
    
asked by anonymous 16.07.2017 / 13:35

2 answers

2

You can use the children method that returns all children of a given element and get length of it.

$('li').each(function() {
  var qtd = $(this).children().length;
  console.log(this.id, qtd);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
   <li id='li1'>
     <a>elemento 1</a>
     <a>elemento 2</a>
     <a>elemento 3</a>
   </li>
   <li id='li2'>
     <a>elemento 1</a>
     <a>elemento 2</a>
     <a>elemento 3</a>
   </li>
</ul>
    
16.07.2017 / 17:34
2

You can assemble an array with the value of how many elements each li has. It would look something like this:

var contador = $('ul li').get().reduce(function(obj, li) {
  obj[li.id] = li.children.length;
  return obj;
}, {});

console.log(contador);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul><liid='li1'><a>elemento1</a><a>elemento2</a><a>elemento3</a></li><liid='li2'><a>elemento1</a><a>elemento2</a><a>elemento3</a></li></ul>

WithmodernjavascriptitwasnotnecessarytojQueryandwouldlooklikethis:

var contador = [...document.querySelectorAll('ul li')].reduce(
  (obj, li) => (obj[li.id] = li.children.length, obj), {}
);

console.log(contador);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id='li1'>
    <a>elemento 1</a>
    <a>elemento 2</a>
    <a>elemento 3</a>
  </li>
  <li id='li2'>
    <a>elemento 1</a>
    <a>elemento 2</a>
    <a>elemento 3</a>
  </li>
</ul>
    
16.07.2017 / 19:18