Unable to show the number of list items in a div using jQuery

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 + '&nbsp;' + 'Colours');
    })
});

Answer №1

To simplify your code, you can use the following:

$('.numberOfColours').html( function(){return $(this).prev().find('li').length} )

$('.numberOfColours').html(function() {
  return $(this).prev().find('li').length
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

This jQuery code selects the numberOfColours elements and calculates the number of list items in the previous element using .html() along with .prev() and .find().

Answer №2

It is recommended to use the .find() method instead of .next()

$(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).find(".numberOfColours").html(colorCount + '&nbsp;' + 'Colours');
    })
});

.next() locates the next relevant sibling (see reference), whereas .find() looks within the parent element. The div containing .numberOfColours is a child element of .search, not its sibling.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The calendar loses its focus when I try to interact with it

One issue I have encountered is that when I click on the input field to display the Calendar component, and then click outside of it to hide it, everything works smoothly. However, the problem arises when I click directly on the icon (Calendar component) i ...

When a parent document is deleted, Mongoose automatically removes any references to child documents

Greetings everyone, thank you for taking the time to read my query. I am looking to remove a child object that is referenced in a parent object. Below is the structure: const parentSchema: = new Schema({ name: String, child: { type: mongoose.Schema. ...

Split-screen homepage design (CSS)

I am trying to design the homepage for my site using only html/css add-ons and without altering any other rule. So far, I have managed to create the blocks themselves but I'm stuck on how to position images behind the buttons, center everything verti ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

Ways to make Selenium detect and interact with a button for clicking:

Is there a way for selenium python to identify this specific button within the HTML code? I've experimented with various tags but have been unsuccessful. driver.find_element_by_class_name('cookie-monster').clickbutton print('s ...

Issue showing hidden content that was loaded using ajax

I'm currently working on a personal project where I am using ajax and jQuery to load elements onto a page. However, I am facing an issue with displaying specific elements under certain conditions after they have been appended to the DOM. There are ce ...

Converting every item's values into keys

Currently, my goal is to export all object values as keys specifically for a tree-shakable import system in a plugin I'm currently developing. The approach involves dynamically importing modules from various directories and subfolders, consolidating t ...

Encounter the "Parameter value missing in web service call" error while attempting to invoke a web service method through jQuery

Below is the code from my aspx file: var DTO = { "'productCategoryId'": "'10'" }; $.ajax({ type: "GET", url: "/WebService/DsmWebServices.asmx/GetProductSubCategory", data: DTO, contentType: "application/json; charset=utf-8", data ...

The disadvantages of manipulating DOM in controllers in AngularJS

Many experts advise against performing DOM manipulations in AngularJS Controllers, but it can be challenging to fully understand why this is considered a best practice. While sources mention issues with testing and the primary purpose of controllers for di ...

Can you explain what purpose does ._[0] serve in args._[0]?

While delving into some Node.js code for creating a small CLI tool, I encountered this underscore notation that seems quite unfamiliar to me. By experimenting with different command line arguments, I've deduced that it essentially involves extracting ...

Button remains behind the image, not moving to the front

I have placed my button on the image, but I want it to sit on top of the image. However, the z-index: 1; property is not working as expected. I have tried all possible position attributes to see if it works, but there was no change. I also added z-index to ...

"Implement a CSS hover effect that targets the child elements within a div, rather than

Looking to experiment with a new product card layout and encountering an issue with the box shadow effect. When hovering over the product card, the hover function only affects the child elements of the div Product-Card hov instead of the actual div itself. ...

What is the best way to send information from a main blade to an included modal?

Trying to implement a functionality where a modal is triggered on clicking a button and an array named $incident is passed through to the properties of a Vue component. What is the correct way to pass data from a parent blade to an included modal? I initia ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

What is the best way to iterate through only the selected checkboxes to calculate their

I am in need of calculating the selected checkboxes only within a table field (harga_obat*jumlah) Below is my foreach data: @foreach ($obat as $o) <tr> <td> <input id="check" type="checkbox" name="select[]" value="{{ $o->nam ...

Switching Atom's Markdown preview theme

I'm exploring ways to customize the theme of the Markdown preview in Atom through cascading stylesheet (CSS) files. Currently, I have the markdown-preview-plus package installed. ...

Utilizing Bootstrap and JavaScript/JQuery for enhancing functionality in Android applications

I created a website that functions well on Google Chrome and other popular browsers. Now, I am looking to publish it for Android using PhoneGap for conversion. A challenge I encountered was that PhoneGap no longer supports Bootstrap or JQuery. Could you pl ...

JavaScript for Designing in Two and Three Dimensions

I need to take a 2D design created in microstation and display it on the web using a tool like javascript, Unity 3D, or another similar option. The web tool should have basic functionality like reshaping or adding new shapes. My current approach involves c ...

Performing asynchronous ajax calls with jQuery

Here is some code I have that involves a list and making an ajax call for each element in the list: util.testMethod = function(list) { var map = new Map(); list.forEach(function(data) { $.ajax({ ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...