1

Preamble - absolutely no jQuery!

I need to monitor a particular DOM element that I have access to via:

var element = document.getElementById('the-element');

When a CSS class is added or removed from element, I need the CSS class name to be delivered to a function.

I am happy to accept reasonable workarounds.

For example:

element.onClassChange(myFunction);

function myFunction(classname, state) {
    console.log('The classname is '+classname+' - '+state);
}
Community
  • 1
  • 1
Knossos
  • 15,802
  • 10
  • 54
  • 91

1 Answers1

0
<!DOCTYPE html>
<html>
<body>

<p id = "classToAdd" classAdded=false>Click the button to trigger a function that will output "Hello World" in a p element with id="demo".</p>

<button onclick="addClassToP()">Click me</button>

<p id="demo"></p>

<script>
function addClassToP() {

 var pEle = document.getElementById("classToAdd");

 pEle.className += "addedClassName"; 
 pEle.classAdded = true;

 pEle.onchange();
}

document.getElementById("classToAdd").onchange = function(){
  if(this.classAdded){
     alert("class added");
     // do something on class added
     this.classAdded = false; // restoring the classAdded notifier attribute
  }
}


</script>

</body>
</html>
  • Sorry about the first answer, I updated the answer in core js :) . I added an attribute classAdded which will determine whether the class is added or not. I added alert code on onchange event. Whenever I add class to the p tag, I set the classAdded attribute to true and then call the onchange() manually. You have to set classAdded to true and call onchange() while adding any class. – Rupesh babu Shrestha Oct 24 '16 at 08:12