Reputation: 11
this is my scenario ; I have an html as below, how can I highlight the search term in the results using Javascript ?
I mean when I type : Ho -> the first 2 letter of HOME will be highlighted. If I search for HOME : the whole word in the result will be highlighted.
Upvotes: 0
Views: 1868
Reputation: 7355
Wrapping the searched term in a span, which is the suggested solution, has two major drawbacks:
The W3C has published a standard for highlighting search terms: the CSS Custom Highlight API. It's implemented in all evergreen browsers (except Firefox at the time of writing).
The idea is to create ranges, and to add these ranges to a highlight registry. Then use CSS to style the highlighted content. This does not change the DOM at all.
Doing it by hand is a bit cumbersome (the range API is tricky), but if you can use an external library it's a one-liner. Assuming you use the value of a search input #search
and that you want to highlight the search term in an element #result
:
<script type="module">
import { highlightSearchTerm } from "https://cdn.jsdelivr.net/npm/[email protected]/src/index.js";
const search = document.getElementById("search");
search.addEventListener("input", () => {
highlightSearchTerm({ search: search.value, selector: "#result" });
});
</script>
Then style the highlight using CSS:
::highlight(search) {
background-color: yellow;
color: black;
}
This is using an open-source library called highlight-search-term, which is compatible with frontend frameworks and contentEditable. It doesn't work in textareas though.
Upvotes: 0
Reputation: 94499
Here is a very basic example:
HTML
Search: <input id="test"/>
<ul id="results"></ul>
Javascript
var results = ["Result1 Description", "Result2 Description", "Result3 Description"];
$("#test").change(function(){
$("#results").empty();
var searchTerm = $(this).val();
for(var i = 0; i < results.length; i++){
if(results[i].indexOf(searchTerm) != -1){
$("#results").append("<li>"+ results[i].replace(searchTerm, "<span class=\"wrap\">" + searchTerm + "</span>") + "</li>");
}
}
});
Working Example http://jsfiddle.net/t3BZ6/
Upvotes: 1