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

141
Visualizações
Find element containing specific text with vanilla js

Is there a way to find HTML Elements that contain specific text in vanilla JavaScript? (Like $( ':contains(text)' ) in jQuery)

*Excluding parent elements. You should only find the element that immediately wraps the text.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use filter:

[...document.querySelectorAll('*')].filter(el => el.textContent.includes(text))

As rightfully pointed out, that will also get you all the ancestors of the elements you're looking for.

So here's a different approach:

const searchString = 'foo';

function findByText(needle, haystack = document) {

  return [...haystack.querySelectorAll('*')].reduce(
    (acc, val) => {
      for (const {
          nodeType,
          textContent,
          parentElement
        } of val.childNodes) {
        if (nodeType === 3 && textContent.includes(needle) && !(parentElement.tagName === 'SCRIPT')) acc.push(parentElement);
      }
      return acc;
    }, []
  );
}

console.log(findByText(searchString));
<div>
  <span>
    <em> foobar ftw</em>
  </span>
</div>

about 4 years ago · Santiago Trujillo 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