HTML DOM Manipulation in JavaScript

rajamuhammadasher

Raja Muhammad Asher

Posted on May 20, 2022

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
💖 💪 🙅 🚩
rajamuhammadasher
Raja Muhammad Asher

Posted on May 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related