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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With