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

301
Views
Problem developing a text searcher javascript

I wanted to highlight/style specific words of a text using js.

index.html

<body>

    <p id="lorem">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. 
        Magni iure doloremque maiores cupiditate quae! 
        Sed dolorum quibusdam ex Lorem vero optio assumenda tenetur iure dolor molestiae, 
        eius eum sequi dolore repellat.
    </p>
    <button onclick="check()">
        check
    </button>

    <script src="./script.js">
    </script>

</body>

script.js

function check(){
  let ipsum = document.getElementById("lorem")
  let vipsum = ipsum.innerHTML

  let elit = vipsum.search(/elit/ig )

  if(elit){
    console.log("so, we have a match")    
    vipsum.substring(elit, 4)

    let highlight = document.querySelector("#lorem").innerHTML[19];
    highlight.style.color: "red"  //Error can't style undefined

  }else{
    console.log("no word matching")
  }

}

I can get the matched string in the console but can't style it in the DOM, I wanted to ask if it was possible to do something like this in javascript.

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

0

In general you can't apply styling to a string you have to apply styling to an html element. When you execute document.querySelector("#lorem").innerHTML it returns a string.

One possible solution is to wrap your matched text in an element which can be styled:

function check(){
  let ipsum = document.getElementById("lorem")
  let vipsum = ipsum.innerText

  let matches = vipsum.split(/(elit)/ig)

  if(matches.length > 1){
    console.log("so, we have a match")
    ipsum.innerHTML = matches.map((str, i) => 
       (i % 2) === 1 ? `<span class=highlight>${str}</span>` : str
    ).join('')
  }else{
    console.log("no word matching")
  }
}
.highlight {color: red;}
<p id="lorem">
Lorem ipsum dolor sit amet consectetur adipisicing elit. 
Magni iure doloremque maiores cupiditate quae! 
Sed dolorum quibusdam ex Lorem vero optio assumenda tenetur iure dolor molestiae, 
eius eum sequi dolore repellat.
</p>

<button onclick="check()">check</button>

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!