czArek czArek - 1 year ago 86
HTML Question

Listen to change class name of button

I want write JavaScript code which should listen to change class name of element from DOM and execute function as below...

console.log("Catch class name change!");

I have button...

<button class="btn-large red" data-bind="text: submitLabel, trueClick: submit,
css: { 'light-skin': ff.DealTicket.useLightSkin, disabled: !isValid() || isOrderPending() ||isSubmitting(), blue: isBuy(), red: !isBuy(), yellow: isOCO() }">Place Sell Trade</button>

...which changes own class name from

<button class="btn-large red">...


<button class="btn-large red dissabled">...

I get this button by


How can I listen to change this name class value ?

I try using eventListener and DOMCOntentLoad, DOMSubtreeModified and it not works.

document.querySelector("").addEventListener("DOMContentLoaded", function(){
console.log("Catch class name change!");

Answer Source

You can use a mutation observer to listen to changes to the element's attributes; when a class is added/removed, the class attribute is updated.


// The function to call when the class changes
function classChanged(b) {
  console.log("The class changed: " + b.className);

// The button
var btn = document.getElementById("the-button");
console.log("Initial class: " + btn.className);

// The mutation observer
var ob = new MutationObserver(function() {
ob.observe(btn, {
  attributes: true,
  attributeFilter: ["class"]

// Just for our example, something to periodically modify
// the classes on the button
var timer = setInterval(function() {
}, 500);
setTimeout(function() {
}, 10000);
.foo {
  color: blue;
.bar {
  color: green;
<button id="the-button" class="foo fuzz">This is the button</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download