0

I'm having some problems with dom changes.

I have 20 li elements in my parent ul. I have changed all li content using the following jquery code:

[...document.querySelectorAll('.signature-discount')].map(item => item.innerHTML = '<span class=\"discount-value\">new content</span>');
$(".product-detail").append("<span class='signature-info'>more new content</span>");

In the page that the li are located there is a infinite scroll. The problem is that everytime the user scrolls to the bottom, 20 new elements are added but their content are not affected by my jquery code.

I have tried using DOMSubtreeModified to listen to changes to my ul classname but it did not work as expected. Can you guys help me? The answer can be either jquery or plain javascript.

ncesar
  • 1,592
  • 2
  • 15
  • 34
  • Selectors and event handlers specified at page load will only match elements which exist at page load. You are adding new elements *after* page load, and your event listeners will not match them - jQuery doesn't know about those new elements. You need to delegate your handlers to an element that exists at load, and filter to match only your target elements. This is a very common problem, and there are many duplicates and variations here on SO, [here's one](https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery). – Don't Panic Aug 26 '21 at 06:56
  • Does this answer your question? [How do I attach events to dynamic HTML elements with jQuery?](https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery) – Don't Panic Aug 26 '21 at 06:56
  • It doenst. This is considering an onClick event, which I don't have. I just append a new content to my DOM and thats it. No interaction from the user besides scrolling. @Don'tPanic – ncesar Aug 26 '21 at 12:59

1 Answers1

0

I did it :)

Since my scenario had no user interaction like most questions about this topic here in SO, I had to watch the user scroll and check the length of my li's.

If the length is bigger than the initial value, then it will re-apply my JS changes.

let initialLength = 20; //this is my initial li length items
$(window).scroll(function() {
    if (document.querySelectorAll(".liProduct").length > initialLength) {
        initialLength = document.querySelectorAll(".liProduct").length; //defining a new initialLength to keep the loop going
        [...document.querySelectorAll('.signature-discount')].map(item => item.innerHTML = '<span class=\"discount-value\">new content</span>');
        $(".product-detail").append("<span class='signature-info'>new content 2</span>");
    }
});
ncesar
  • 1,592
  • 2
  • 15
  • 34