How to count the elements of a jquery li

Asked

Viewed 1,154 times

1

Have to count the elements that are inside the li, but let it be by step, for example first take the li1 and count the elements that in the case have to go back 3 and then pass 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>
  • An Array that contains objects {id: <id of the li> tag, counter: <counter of li>} elements would suit you? With it you could implement an iterator to compose whatever computation you want. And this? It really needs Jquery?

2 answers

2


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

$('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>

  • It solves the problem, but this can count more than necessary if there are other things that should not be told inside the li. It would not be better to specify which element to count?

2

You can mount an array with the value of how many elements each li has. It would be 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>
   <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>

With modern Javascript it wasn’t even necessary jQuery and would look like this:

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.