简体   繁体   中英

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


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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM