Search code examples
javascriptjquerymutation-observers

Fire jquery based on mutation on same class with multiple instances


I've applied the mutationobserver to determine a class inclusion within an element (.wq_singleResultWrapper) and as such add another class to a different element (#prizeentry)

The code i'm working with is essentially a "personality" quiz with 4 results at the end. Each within a wrapper (.wq_singleResultWrapper).

IF the result is the first result the jquery is processed fine. However will not function if any of the other results show.

var $div = document.getElementsByClassName(
    "wq_singleResultWrapper"
);

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === "class") {
      var attributeValue = $(mutation.target).prop(mutation.attributeName);
      $('#prizeentry').addClass("visable");
    }
  });
});

observer.observe($div[0], {
  attributes: true
});

So below is the following expected result: as you can see a class inclusion on the second div would trigger the addClass in the below div (as previously stated this would only work if the first div has the class inclusion.

<div class="wq_singleResultWrapper"></div>
<div class="wq_singleResultWrapper result"></div>
<div class="wq_singleResultWrapper"></div>
<div class="wq_singleResultWrapper"></div>
<div id="prizeentry" class="visable"></div>

see following example https://jsfiddle.net/2d8hb3n0/23/

I am using the mutationobserver as i do not have access to the jquery thats adding the class inclusion.


Solution

  • The first result works because only $div[0] is observed. $div contains all results so iterate $div should work.

    Array.from($div).forEach((div) => {
      observer.observe(div, {
        attributes: true, 
        subtree: true, 
        childList: true
      });
    })