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