Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
How to get observed element by a mutation observer

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!