Skip to content
Advertisement

How to add event listener for a dynamically appended element’s classList

I have a div with the className mic-button, it is a dynamically appended element. I want to listen for change in it’s classList, like, I want to trigger function foo() when any class is added or removed from the element. I prefer to use Vanilla Js. I searched in internet, and i only got solution with JQUERY.

Thanks, Rob Wilson

Advertisement

Answer


I’m pretty sure there is no event for this, but maybe you can check every second for changes in the ClassName.
Like this:

var current = "mic-button";
window.setInterval(() => {
  var classN = document.querySelector(".mic-button").className;
  if (classN != current) {foo(); current = classN;}
}, 1000);

function foo() {
  console.log("foo");
 }
<button class="mic-button">Mic-button</button><br />
<button onclick="document.querySelector('.mic-button').classList.add('foo');">add class</button><br />
<button onclick="document.querySelector('.mic-button').classList.remove('foo');">remove class</button>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement