Raja Muhammad Asher
Raja Muhammad Asher

Raja Muhammad Asher

HTML DOM Manipulation in JavaScript

Photo by Jackson So on Unsplash

HTML DOM Manipulation in JavaScript

Raja Muhammad Asher's photo
Raja Muhammad Asher
·Apr 30, 2022·

1 min read

We can use setInterval() method of JavaScript to monitor changes in the DOM after regular intervals. For example, we have to add event listener to add-to-cart button for tracking purposes but there are few products that load after an ajax call. How can you differentiate between the newly loaded add-to-cart buttons and the ones you have already added the event listeners?

We can use setAttribute() method to add our custom attribute to distinguish between them. We will use querySelector() method to select only those buttons who do not have our custom attribute set on it. Add the event listener and then set our custom attribute to them.

Here is the code sample

setInterval(() => {
    try {
      document.querySelectorAll('.add-to-cart:not([custom-attrib])').forEach((selector) => {
        selector.addEventListener('click', () => {
          // your code for execution
        });

        selector.setAttribute('custom-attrib', true);
      });
      }
    } catch (err) {
      // continue
    }
  }, 750);
 
Share this