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

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

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 Denunciar

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 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