Within this section, there are multiple paragraphs and an input field. The concept is simple: the user inputs text into the box, then hits "ENTER" to trigger a jquery function below.
The process involves identifying matches between the paragraph content and the user input. When a match is found, the paragraph's HTML is essentially updated with a span element wrapping the matching text. This allows for easy CSS styling to highlight the matched text.
However, a current issue I'm facing is that when the text is replaced, it affects all instances of that specific HTML element type on the entire page. It may be challenging to explain in words, so feel free to explore the behavior using this provided fiddle. Enter easily identifiable text and observe the outcome.
Is there a way to regenerate the text element by element instead of duplicating every instance?
<input type="text" id="searchbox">
<p>Let's get some text to test</p>
<p>This is another paragraph</p>
function searchHighlight(searchText){
if(searchText){
// Variable declaration for question content
var content = $('p').text();
// Variable declaration for search phrase
var searchExp = new RegExp(searchText, "ig");
// Variable declaration for match identification
var matches = content.match(searchExp);
// If text is found within the QUESTION, proceed as follows...
if(matches){
$("p").html(content.replace(searchExp, function(match){
return "<span class='selected'>" + match + "</span>";
}))
}
else{
$("#searchbox").css("border", "1px solid red")
}
}
Access the demo through this link: https://jsfiddle.net/awv5r1f0/1/