If I have two span elements with class "selected" changing width based on selection, I just need to determine when span2 is selected.
<span class="swatch swatch-image span1">
<span class="swatch swatch-image span2 selected">
I want to detect which span is selected (has class "selected") and then show or hide a div elsewhere. Is this possible?
I've attempted the following approach:
let targetNode = document.getElementsByClassName('swatch swatch-image span2 selected');
const config = { attributes: true, childList: false, subtree: false, attributeFilter: ['class'] };
const callback = function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.attributeName === "class") {
var classList = mutation.target.className;
if(/red/.exec(classList).length > 0) {
console.log('Found match');
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
observer.disconnect();
Is MutationObserver the correct method to listen for the selected span? I am not very familiar with javascript, do I need to call MutationObserver in a certain way after setting up the code?