Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of li element and add class

I am trying to count li elements, and addClass to another div.

For example:

$('.box2').addClass(function(){
  return 'list' + $(this).find('.box1 li').length;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="box1">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>


<div class="box2">text</div>

This should be like this

<div class="box2 list3">text</div>

But I don't know why when I check on the DOM code,

<div class="box2 list0">text</div>

I get this result.

What do I need to fix the code? Please help.

like image 273
kk kk Avatar asked Mar 11 '19 05:03

kk kk


Video Answer


2 Answers

Your query looks for .box1 li within .box2, though these two elements are siblings. Therefore, your find() query will always return 0.

For your query to work, your HTML would need to look like this:

<div class="box2">text
  <ul class="box1">
    <li>a</li>
    <li>b</li>
    <li>c</li>
  </ul>
</div>

Without altering the structure of your HTML, you can get this to work by accessing .box1 li directly:

$('.box2').addClass(function(){
  return 'list' + $('.box1 li').length;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="box1">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

<div class="box2">text</div>
like image 87
Andy Hoffman Avatar answered Sep 28 '22 09:09

Andy Hoffman


Here $(this) is referring to box2 element.Only $('.box1 li').length is what you required

$('.box2').addClass(function() {
  return 'list_' + $('.box1 li').length;
});
.list_3 {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="box1">
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
<div class="box2">text</div>
like image 45
brk Avatar answered Sep 28 '22 07:09

brk