Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!