Keep Array up-to-date as new elements appear on the webpage

Currently, I am developing a Chrome extension that requires me to retrieve the total number of books available in a library. The current code snippet is functioning correctly, but the issue arises when the page loads only half of the books initially and updates as you scroll down further, causing the array not to update accordingly. Is there a way to automatically refresh the array to reflect these changes?

let list = document.querySelectorAll("ul > li");
let numBooks = [];

for (let i = 0; i < list.length; i++) {
  numBooks.push(i + 1);
}

console.log(numBooks);

Answer №1

// Declaring variables
let itemList = document.querySelectorAll("ul > li");
let mainList = document.querySelector("ul");
let bookNumbers = [];

// Adding books to array
for (let index = 0; index < itemList.length; index++) {
  bookNumbers.push(index + 1);
}

// Observing changes
const mutationObserver = new MutationObserver(function (mutations) {
  mutations.forEach(function (mutation) {
    if (mutation.addedNodes.length) {
      // Creating element for displaying book count
      let myUrl = "myurl";
      let numBooks = bookNumbers.length / 10;
      let numChanges = mutation.addedNodes.length - 1;
      if (myUrl == window.location.href) {
        let elem = document.createElement("span");
        elem.innerHTML = numBooks + numChanges;

        let parentElement = document.getElementsByTagName("h2")[0];
        parentElement.appendChild(elem);
      }
    }
  });
});
mutationObserver.observe(mainList, {
  childList: true,
});

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

Customizing Django forms.Textarea in template or declaring in models is essential for creating a unique

Within my models, I have a forms.Form that includes a textarea field: answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type your answer...", "rows":6, "cols":45}), max_length=150) When it comes to views: ...

Is it possible to automatically play a sound clip when the page loads?

Is there a way to automatically play a sound clip when my page loads? Are there any specific JavaScript or jQuery methods I can use for this, as I am developing my page using PHP. ...

Displaying a clock using PHP

Seeking a way to display server time on my website, I have successfully implemented client-side time using JavaScript. How can I now showcase the server time? Are there any ZendFramework classes that can assist with this? Currently, I am utilizing the fo ...

Socket.on seems to be malfunctioning

Currently, I am in the process of creating a message board for practice purposes and have successfully implemented notifications and a chat application using socket.io. My next goal is to add basic video call functionality, but I have encountered some dif ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

MongoDB's Data-Driven Dropdown

I have a database named Staff in mongoDB, which includes a collection called records. Within this collection, there is a field named workgroup that contains entries such as "management", "union", "support staff", and more. My goal is to populate a dropdow ...

Manage the orientation of an object circling a sphere using quaternions

My latest game features an airplane being controlled by the user from a top-down perspective, flying over a spherical earth object. The airplane has the ability to rotate left or right by using the arrow keys on the keyboard, and can accelerate by pressing ...

Adding elements in the center of a given array

I have a situation where I need to modify a char array named encoded by inserting 3 characters in the middle while shifting the remaining characters over. Is there a way to achieve this? The code snippet that I have attempted only replaces the next two ch ...

How can we stop every tab pane in (bootstrap five) from sharing the same scroll position? Each tab is currently synchronized with the scroll position of the others

In Bootstrap 5, the scroll position remains the same when switching between tabs in the tab pane. Whether moving from tab #1 to tab #2, both tabs are at the identical scroll position, failing to preserve each tab's specific location. <div class=&qu ...

React-Query will not automatically refetch data on mount when using an invalidated query

I made sure my components do not always refetch when they mount and already have the query in the cache by implementing the following solution: export const App = ({ props }) => { const queryClient = new QueryClient({ defaultOptions: { queri ...

Display recommendations as soon as a specific character is entered in the text box

Issue Description: I am looking to implement a specific feature using Javascript or JQuery. When a user types a designated character, such as the @ symbol, in a text box, I would like the values of an array to be displayed in a drop-down menu. For example, ...

Annoying underlines from JavaScript active links - no thanks!

Today I am facing a problem. I want to create a script that will emphasize the active link that I clicked on. I'm not sure how to do this. Can you provide me with some advice? I have an idea, but I'm not certain if it's the best solution. ...

Identifying unique characters such as ^A within a byte array

Is there a way to detect and remove special characters like ^A in a byte array file? ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Restrict HTML Elements Based on Their Size

I have a text file with a substantial amount of content that I need to display in an HTML format. The challenge is that I only want to show a portion of the text on the screen, but I am unsure of the exact amount that needs to be displayed. What I do know ...

Ways to run a javascript command just a single time

I have a function that makes an HTTP GET request to compare a given value with elements in an array. If there's no match, I want to add the value to another array. The issue is that duplicates are being added to the array because of multiple loop iter ...

How can I toggle input disablement in Bootstrap depending on switch selection?

I have been exploring the Bootstrap 5 documentation in search of a way to disable other input fields when a toggle switch input is set to 'off'. The parent element for this scenario is #member_form, and the switch itself is identified as 'to ...

Triggering an event just once upon sending an Ajax request with jQuery

I've implemented a feature where I have dropdown menus populated from SharePoint using SPServices, and it's working well. However, when I click on a button to load data from SharePoint and use the dropdown selections as filters for populating a t ...

Using Typescript with Material UI Select

I have implemented a dropdown menu using Material UI select labeled "Search By." When the menu is clicked, it displays a list of options. I aim to store the selected option and update the label "Search By" with the chosen option. export default function U ...