How to get observed element by a mutation observer

Viewed 44

Hi,

I have an observer and I call it like this:

myobserver.observe(mydiv, {childList : true, subtree : true, attributes : true});

I need to fetch the observed element, something like this

myobserver = new MutationObserver((mymutations) => {
 console.log(observed);  //should output "mydiv" always regardless of the mutation
});

I tried mymutations.target but that wont do because it will get me a different element if the mutation is in one of the children. Is there any way to do it?

Thank you

1 Answers

Try adding an attribute to the observed element (parent) and then use Element.closest() to find it from within the mutation callback.

const div = document.querySelector('div');
const span = document.querySelector('span');
const section = document.querySelector('section');
const blockquote = document.querySelector('blockquote');

const myobserver = new MutationObserver((mymutations) => {
  const observed = mymutations.map((mutation) => mutation.target.closest('[data-observed]'));
  console.log(observed);
});


div.setAttribute('data-observed', '');
myobserver.observe(div, {
  childList: true,
  subtree: true,
  attributes: true
});


section.setAttribute('data-observed', '');
myobserver.observe(section, {
  childList: true,
  subtree: true,
  attributes: true
});


setTimeout(() => span.innerHTML = 'Something else', 500);

setTimeout(() => blockquote.innerHTML = 'Something else', 500);
<div>
  <span>Something</span>
</div>

<section>
  <blockquote>Something</blockquote>
</section>

Related