JSFiddle - React, Tailwind, and code Playground
by Kevin Mwangi
HTML
<p>Open and watch the console. Then press the button to see mutation reports and jQuery used on
observer data.
</p>
<div>
<button>Toggle span contents</button>
</div>
<span id="payload" class="myclass">
<span class="myclass2">My <span class="boldly">vastly</span> improved</span>
text.
</span>
CSS
div {margin: 1em;}
.myclass2 {font-size: 18px !important;}
span.boldly {font-weight: bold;}
JavaScript
var targetNodes = $(".myclass");
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver (mutationHandler);
var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true };
//--- Add a target node to the observer. Can only add one node at a time.
targetNodes.each ( function () {
myObserver.observe (this, obsConfig);
} );
function mutationHandler (mutationRecords) {
console.info ("mutationHandler:");
mutationRecords.forEach ( function (mutation) {
console.log (mutation.type);
if (typeof mutation.removedNodes == "object") {
var jq = $(mutation.removedNodes);
console.log (jq);
console.log (jq.is("span.myclass2"));
console.log (jq.find("span") );
}
} );
}
/**************************************
jsFiddle only
*/
$("button").click ( function () {
var target = $("#payload");
if (/censored/i.test (target.text () ) ) {
target.html ('<span class="myclass2">My <span class="boldly">vastly</span> improved</span> text.');
}
else {
target.html ('[censored!]');
}
} );