I am having an issue with my Jquery code that is supposed to find the number of list items (<li>
) in a unordered list (<ul>
). I want to display this count in a div with a specific class, but my current code is not working as expected. However, when I use the alert function, the result seems correct.
The problem arises when trying to show the count in place of the text 'Test' within the div. Instead of displaying the actual count, it just shows the word 'Test'. Interestingly, if I remove the div from the id attribute such as result-item-1
, the code works fine.
To see live example and code, you can visit this JS Fiddle Link.
Here is the code snippet:
<div id="result-item-1" class="search" data-search-position="1" style="width: 50%;">
<div class='item-colours-result'>
<ul class="">
<li>1</li>
<li>2</li>
</ul>
</div>
<div class="numberOfColours">Test</div>
</div>
<div id="result-item-2" class="search" data-search-position="2" style="width: 50%;">
<div class='item-colours-result'>
<ul class="">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<div class="numberOfColours">Test</div>
</div>
<div id="result-item-3" class="search" data-search-position="3" style="width: 50%;">
<div class='item-colours-result'>
<ul class="">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<div class="numberOfColours">Test</div>
</div>
Jquery:
$(document).ready(function() {
$('.search').each(function(index, item) {
var colorCount = $(item).find('.item-colours-result ul li').length;
//alert(item.id+':'+colorCount)
$(item).attr('data-search-position', colorCount);
$(this).next(".numberOfColours").html(colorCount + ' ' + 'Colours');
})
});