Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda