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

176
Views
Highlight word in webpage without .innerhtml

I want to highlight a word in a page without involving the document.body.innerHTML as this totally alters the functionality of the page.

Is there any other way to do it?

Right now I am using this code to highlight

document.body.innerHTML= document.body.innerHTML.replace(/TEST/g, function(m){
    return '<span style="background-color:YELLOW">'+m+'</span>'
}

Thank you

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If I understand your problem correctly, I would suggest to retrieve the DOM elements with the relevant content, get the content, and finally surround it with a styled span element.

const $matchedElements = document.querySelectorAll("p");

$matchedElements.forEach(($element) => {
  if ($element.innerHTML.match("SampleCollected")) {
    const $mySpan = document.createElement("span");
    $mySpan.style = "background-color:yellow";
    $mySpan.innerHTML = $element.innerHTML;

    $element.innerHTML = ""
    $element.appendChild($mySpan)
  }
});
<!DOCTYPE html>
<html>
  <head>
    <title>Example</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <p>
      SampleCollected
    </p>
    <p>
      SampleNotCollected
    </p>
    <p>
      SampleCollected
    </p>

    <script src="src/index.js"></script>
  </body>
</html>

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!