DEV Community

Raja Muhammad Asher
Raja Muhammad Asher

Posted on • Originally published at rajamuhammadasher.com

HTML DOM Manipulation in JavaScript

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)