Reputation: 1220
I am using a third party script that I don't want to modify.
In this script, there is a function that I need to listen for that adds a class to a dom node.
function _showElement(targetElement) {
targetElement.element.className += 'this-class';
}
What I would like to do is listen for this element to be called and whenever it does add a class to its parent with pure javascript.
function addThis() {
var doc = document;
liveEl = doc.getElementsByName("this-class");
// Code to add class to parent
}
Upvotes: 1
Views: 320
Reputation: 27823
The simplest "brute force" solution is to hijack (redefine) the function:
function _showElement(targetElement) {
console.log('original');
}
_showElement(); // hijacked
function _showElement(targetElement) {
console.log('hijacked');
}
Unfortunately i don't think you can save the original behavior of the function, so you need to copy-paste it:
function _showElement(targetElement) {
targetElement.element.className += 'this-class';
addThis()
}
Another solution, more specific to your problem (do something when the className of an element changes) you can listen for mutation events on the DOM:
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
Basically you create a MutationObserver and observe attribute changes on your element. It might not be such a great solution if you need to track all the nodes, but in some cases it might come in handy.
Upvotes: 1
Reputation: 1752
You can't do this directly. You can't listen event like dom attribute change. However, there is a way that you can identify the event which is trigger _showElement
and attach a one more handler to the event which should call addThis
function.
Upvotes: 0