Using JavaScript, I have implemented a search keyword function that highlights specific words in a paragraph. However, I am facing an issue. Currently, when searching for the next keyword, the previously highlighted text remains in red instead of reverting back to the original black color. How can I modify this code to ensure that the previous search keyword is not highlighted in red when searching for a new keyword? Any suggestions on optimizing this solution would be greatly appreciated. Thank you in advance for your assistance.
let search = document.querySelector('#js-search');
let content = document.querySelector('p');
let key = document.querySelector('#keyWord').value;
function highlight(content, key){
return content.replace(new RegExp(key,'gi'),(match)=>{
return `<span style="color:red">${match}</span>`;
});
}
search.addEventListener('click',() =>{
const keyword = $('#keyWord').val();
const matchs = $("p:contains("+ keyword +")");
matchs.each(function(){
const content = $(this).html();
$(this).html(highlight(content,keyword));
});
});
.red{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="keyWord" type="text"><button id="js-search">search</button>
<ul>
<li>
<h1>eturn problem</h1>
<p>I am an example of related content</p>
</li>
<li>
<h1>credit card problem</h1>
<p>This is about credit card issues, you can search for keywords to find keywords</p>
</li>
<li>
<h1>order cancellation problem</h1>
<p>order cancellation problemThis is a sample text of random typing content</p>
</li>
</ul>