DEV Community

Raja Muhammad Asher
Raja Muhammad Asher

Posted on • Originally published at rajamuhammadasher.com

4 2

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay