Count Number Of Li Element And Add Class
Answer :
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>
this is not pointing to the element you are thinking, it is referring to DIV element on which the addClass()
is invoked and this element does not have .box1 li
. Thus find()
is failing to refer your intended element.
Simply use:
$('.box1 li').length
$('.box2').addClass(function(){
console.log(this.nodeName); // DIV
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>
Comments
Post a Comment