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

223
Visualizações
Is it possible to detect a change of <select> length immediately using MutationObserver?

I have a <select> tag that is populated and updated dynamically with <option> tags. Currently I let the MutationObserver change the local length variable that keeps track of the .length property of the <select>. The issue is that it seems to be some delay before the MutationObserver actually updates the value and oftentimes the variable is not the current length of the select list. Is there some workaround or is this the nature of MutationObserver?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's a demonstration of the behavior that you described. Now matter how many times I run it, the longest delta I see is always less than 1.5 ms. Is that what you mean by "delay"?

I wanted to write this as a comment initially, but there's no way to show a demo on-site in a comment, so I'm writing an answer. If you can refine your question to clarify or differentiate the issue, then I can potentially update this answer to address it (or delete it if it's no longer relevant to the new information).

<div>
  <select>
    <option>No options</option>
  </select>
</div>
<script type="module">

const select = document.querySelector('select');
let {length} = select;
let previousTime = performance.now();

const observer = new MutationObserver((mutations) => {
  for (const {addedNodes, removedNodes, type} of mutations) {
    if (type !== 'childList') continue;
    for (const node of addedNodes) {
      if (node.tagName !== 'OPTION') continue;
      length += 1;
    }
    for (const node of removedNodes) {
      if (node.tagName !== 'OPTION') continue;
      length -= 1;
    }
  }
  const deltaMs = performance.now() - previousTime;
  console.log('Observed', `length: ${length} (${deltaMs} ms)`);
});

observer.observe(select, {childList: true});

const setOptions = (items) => {
  const options = items.map(str => {
    const option = document.createElement('option');
    option.textContent = str;
    return option;
  });

  while (select.firstChild) select.firstChild.remove();
  for (const option of options) select.appendChild(option);
  previousTime = performance.now();
  console.log('Set', `length: ${select.length}`);
};

const delay = (ms) => new Promise(res => setTimeout(res, ms));

setOptions(['a', 'b', 'c']);
await delay(2e3);

setOptions(['none']);
await delay(2e3);

setOptions(['one', 'two', 'three']);
await delay(2e3);

observer.disconnect();

</script>

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