1

I'm working on a chrome extension where I need to gather the total number of books in a library. The code below works fine, however, the page where I'm getting the data only loads half of the books at once until you scroll down further and the array doesn't update accordingly. Is there a way to automatically update the array to keep up with the changes?

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

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

console.log(numBooks);
3
  • 3
    A MutationObserver could help you update the array if something in the DOM changes. Commented May 12, 2021 at 6:46
  • which page ? usually how you approach this is to use timers and get the scroll element and programatically call scroll. or else you could check how the page is loading the next set of books and may be you can fetch them urselves. Commented May 12, 2021 at 6:47
  • @Reyno I'll try this method and post my results. Thanks. Commented May 12, 2021 at 6:54

1 Answer 1

1
// Variables
let list = document.querySelectorAll("ul > li");
let mlist = document.querySelector("ul");
let numBooks = [];

// Push books to array
for (let i = 0; i < list.length; i++) {
  numBooks.push(i + 1);
}

// Observe changes
const observer = new MutationObserver(function (mutations) {
  mutations.forEach(function (mutation) {
    if (mutation.addedNodes.length) {
      // Create Element: Book Count
      let url = "myurl";
      let nBooks = numBooks.length / 10;
      let nChanges = mutation.addedNodes.length - 1;
      if (url == window.location.href) {
        let el = document.createElement("span");
        el.innerHTML = nBooks + nChanges;

        let par = document.getElementsByTagName("h2")[0];
        par.appendChild(el);
      }
    }
  });
});
observer.observe(mlist, {
  childList: true,
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.