Is there a way to dynamically count the length of an element or class in realtime using JavaScript?

If there are currently 5 divs with the class name "item" and a new unknown number of divs with the same class name "item" are dynamically added in real time, I want my result to display the total number of divs present at that moment (i.e., 5 + n).

Note: There are no click or hover events involved.

<div class="wrapper">
      <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
      <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
      <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
      <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
      <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
</div>

<script>
var numItems = $('.item').length;
console.log(numItems);
</script>

Currently, this code only provides the result on the first load, but I need the result to be updated dynamically in real time.

Answer №1

If you want to keep an eye on changes happening within the parent node called wrapper, you can utilize the power of a Mutation Observer. This tool allows you to set up a callback function that gets triggered whenever there are mutations in the DOM element.

Take a look at the code snippet below for a practical example:

const callback = () => {
  var numItems = $('.item').length;
  console.log(numItems);
};

const targetNode = $('.wrapper').get(0);
const config = {
  attributes: true,
  childList: true
};
// Begin observing changes in the wrapper node
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

// Display current count of items
callback();

// Function to dynamically add more nodes
setInterval(() => {
  const node = $("<div>").attr('class', 'item');
  $('.wrapper').eq(0).append(node);
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
  <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
  <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
  <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
  <div class="item"><img src="https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940g"></div>
</div>

Remember to consult the Browser_compatibility guide for Mutation Observer support.

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

Encountered a problem when attempting to upload images to Cloudinary through the front-end and save the information in a MySQL database using Axios on Node JS

I am currently working on a web application using React. I have implemented a form where users can input text data and upload multiple image files. The goal is to store the submitted images on Cloudinary along with other text data in a MySQL database. Unf ...

TemplateUrl malfunctioning

While experimenting with basic Angular code, I encountered an issue where everything was functioning correctly when using template, but not when switching to templateUrl. I did not provide the previous code as it was working fine except for this specific c ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

Utilizing Angular JS to ensure services are universally accessible across controllers and views

Imagine we have a service like this: myApp.factory('FooService', function () { ... Now, from a controller, the code would look something like this: myApp.controller('FooCtrl', ['$scope', 'FooService', function ($s ...

Utilizing the Selenium driver to test the functionality of SpreadJS

Is there a way to trigger click events based on cell position in spreadJs? I attempted the following: sheet.setActiveCell(3,3); sheet.cellClick(); as well as sheet.getCell(3,3).cellClick(); However, I have not been successful. Any help or suggestions ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

Obtaining the href value in server-side code when the anchor tag is clicked

I am facing a scenario where there is a table with an anchor tag in each row. Upon clicking the anchor link, I am able to retrieve the href value using jQuery and bind it to a hidden field. Now, my challenge is to pass this hidden field value to the server ...

Make sure that the function displays the output once it has been received using the jQuery.get method

This script fetches data using the $.get method from an XML file on an ASP ashx server: $.get("http://www.example.com/example.ashx", { From: txtFrom, To: txtTo, Date: txtTime }, function (data) { var arr ...

How to include a listview in the footer navbar using jQuery Mobile

Is there a way to include areas instead of links in the footer navbar, and then incorporate a list view within one of those areas? The navbar only seems to accept anchors, not divs, and the styling of the list view is not displaying correctly in the provid ...

Issue encountered during rendering: The function used is not a filter

Everything works fine with the search filter and pagination on the initial load. However, upon clicking to go to the next page, an error occurs stating **'Error in render: "TypeError: this.tickets.filter is not a function"'**. This issue can b ...

How can we adjust the number of items based on the width of the viewport in Vue.js?

Imagine having a template that showcases a specific number of items, like this: <template> <div> <div v-for="item in items.slice(0, 10)" :key="item" /> </div> </template> How can I adjust the numbe ...

Align the icon and text both vertically and horizontally in the center

I have a collection of links: <ul> <li><a href="#" class="icon26 icon1">Link 1</a></li> <li><a class="icon26 icon2">Link 2</a></li> </ul> Each link comes with an icon. My ...

Utilize the three.js library within a Vue component by importing it and incorporating its

Can someone please help me understand the proper way to import and utilize the three.js library in a vue component? Despite my extensive research, it seems that most individuals use the following code line to import three.js into a vue component. However, ...

transferring a variable that has already been utilized through ajax

I have implemented a jquery datepicker on my webpage. Next to the datepicker, there is a section that displays events when you hover over a date. I was able to successfully get the date into the header of this section. However, I am struggling with transfe ...

Leveraging AngularJS $promise in conjunction with NgResource

As I delve into the world of AngularJS, I have encountered promises which have proven to be quite beneficial in my learning journey so far. Now, I am eager to explore the optional library resource.js in AngularJS. However, I stumbled upon examples that lef ...

Image not displayed after uploading to presigned AWS S3 URL in React Native

I've been attempting to upload an image to AWS S3 in my React Native app (expo managed workflow) but I keep encountering the issue of the file being empty. Strangely, there are no errors thrown during the process. Even after trying to use the Uppy AWS ...

Transferring data between different elements in a React application

I am currently learning React and facing some challenges in terms of passing data between components. Even after reviewing various tutorials and blogs, I am still struggling to make things work. Within my project, I have two child components named Body-c ...

Implementing a JavaScript Module Using JavaScript

I have encountered a simple problem. I am trying to use two JavaScript files: one following the module pattern and another one that calls the first one. I have tested all the code using Node.js and everything works fine when it is all in one file. However, ...

Numerous toggles available for the mobile version

Hey there, I need some help! I have a footer navigation on my desktop website with 3 Ul elements. I want to turn each Ul into a toggle for the mobile version. Can anyone assist me with this? Thanks in advance! <footer class="footer"> <d ...

Obtain the value of "Placeholder" using JavaScript in Internet Explorer without the need for JQuery

I have some custom Javascript code that checks for browser support of placeholders and creates them if not supported. This solution works on some older browsers, but not all, especially IE. The issue I am facing is retrieving the "Placeholder" value; curr ...