Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda