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

160
Visualizações
How to apply Javascript Highlight specific word function to a class or id

How to apply Javascript Highlight specific word function to a class or id

function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {
 const flags = caseSensitive ? 'gi' : 'g';
 keywords.sort((a, b) => b.length - a.length);
 Array.from(elem.childNodes).forEach(child => {
 const keywordRegex = RegExp(keywords.join('|'), flags);
 if (child.nodeType !== 3) {
  highlight(child, keywords, caseSensitive, cls);
 } else if (keywordRegex.test(child.textContent)) {
  const frag = document.createDocumentFragment();
  let lastIdx = 0;
  child.textContent.replace(keywordRegex, (match, idx) => {
    const part = document.createTextNode(child.textContent.slice(lastIdx, idx));
    const highlighted = document.createElement('span');
    highlighted.textContent = match;
    highlighted.classList.add(cls);
    frag.appendChild(part);
    frag.appendChild(highlighted);
    lastIdx = idx + match.length;
  });
  const end = document.createTextNode(child.textContent.slice(lastIdx));
  frag.appendChild(end);
  child.parentNode.replaceChild(frag, child);
   }
  });
  }

  highlight(document.body, ['lorem', 'amet', 'autem']);
.highlight {
 background: lightpink;
 }
<div class="mytext"><p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing 
elit. Est vel accusantium 
totam, ipsum delectus et dignissimos mollitia!</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis.
<small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas 
perferendis dolores ducimus velit error voluptatem, qui rerum modi? this is amet in the 
wall</small>
</p>

<div contenteditable="true">hello amet this</div>
  </div>

now this function applies to everything on the website, need to apply to class .mytext

I'm new to javascript so a demo example would be helpful.

thank you

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

0

search the element you want first, and then use your highlight function.

example here:

function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {
 const flags = caseSensitive ? 'gi' : 'g';
 keywords.sort((a, b) => b.length - a.length);
 Array.from(elem.childNodes).forEach(child => {
 const keywordRegex = RegExp(keywords.join('|'), flags);
 if (child.nodeType !== 3) {
  highlight(child, keywords, caseSensitive, cls);
 } else if (keywordRegex.test(child.textContent)) {
  const frag = document.createDocumentFragment();
  let lastIdx = 0;
  child.textContent.replace(keywordRegex, (match, idx) => {
    const part = document.createTextNode(child.textContent.slice(lastIdx, idx));
    const highlighted = document.createElement('span');
    highlighted.textContent = match;
    highlighted.classList.add(cls);
    frag.appendChild(part);
    frag.appendChild(highlighted);
    lastIdx = idx + match.length;
  });
  const end = document.createTextNode(child.textContent.slice(lastIdx));
  frag.appendChild(end);
  child.parentNode.replaceChild(frag, child);
   }
  });
  }
var byClass = document.getElementsByClassName('mytext')[0];

  highlight(byClass, ['lorem', 'amet', 'autem']);
.highlight {
 background: lightpink;
 }
<div class="mytext"><p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing 
elit. Est vel accusantium 
totam, ipsum delectus et dignissimos mollitia!</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis.
<small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas 
perferendis dolores ducimus velit error voluptatem, qui rerum modi? this is amet in the 
wall</small>
</p>

<div contenteditable="true">hello amet this</div>
  </div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You apply your highlight function to document.body. Instead, you should apply it to element with id:

highlight(document.getElementById('your_id'), ['lorem', 'amet', 'autem']);

Or to all elements with some class:

document.querySelectorAll('.your_class').forEach(function(element) {
  highlight(element, ['lorem', 'amet', 'autem']);
});
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