How to Highlight the Searched String Result using JavaScript ?
Last Updated :
12 Apr, 2023
Given below is an HTML document which is basically about how to highlight the searched string result. In this article, we are using HTML, CSS, JavaScript, Bootstrap and mark.js to make our website more effective. Moreover, exclusively for highlighting the searched string among a given context or paragraph, mark.js plays a vital role in this particular code. Before approaching this problem, keep a mark of my words that, the problem can be solved by many other approaches but I think this can also be a way better approach towards this given problem.
What is mark.js?
mark.js is a simple JavaScript tool that is used to highlight the text. Which is used to dynamically mark search terms or custom regular expression and offer some built-in options like diacritics support, separate word search etc.
Approach:
- First thing first when you are entering some string on the search box and press the search button then a simple JavaScript function will call named as highlight() which has the main role is to highlight the search text that you had entered in the search box. In this small, we are going to use mark.js code to highlight the text.
- There are many built-in functions in mark.js but we are using two functions for our requirement that is mark() and unmark() function respectively. Here mark() is used to highlight the search text and unmark() is used to remove highlighting the text that is highlighted before.
Syntax of mark():
var context = document.querySelector(".context");
var obj = new Mark(context);
obj.mark(searchkeyword [, options]);
- Let's understand this code in a bit of technical manner,
- First we declare a variable which contains context from which it is going to find and highlight the searched text.
- Create an object of the mark and then call the mark() method through the obj that you create previously.
- It takes two parameters with it i.e, one is searched keyword and another is optional.
Syntax of unmark():
var context = document.querySelector(".context");
var obj = new Mark(context);
obj.unmark(options);
- Hope you have successfully followed the above steps in order to make changes in the color of the particular highlighted text. But here make sure that there should not be any string left highlighted with any particular color if it is so then don’t forget to un-highlight the text which was searched previously. Thereafter, mark the new string which is to be searched and you can change its color according to your convenience.
- For more information follow this page.
Example:
HTML
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<!-- CDN of fontawsome -->
<link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- CDN of Bootstrap -->
<link rel="stylesheet" href=
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
integrity=
"sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
crossorigin="anonymous">
<!-- CDN of mark.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js"
integrity=
"sha512-5CYOlHXGh6QpOFA/TeTylKLWfB3ftPsde7AnmhuitiTX4K5SqCLBeKro6sPS8ilsz1Q4NRx3v8Ko2IBiszzdww=="
crossorigin="anonymous">
</script>
<!-- CDN of google font -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@500&display=swap'
);
</style>
<style>
mark.a0 {
color: black;
padding: 5px;
background: greenyellow;
}
mark.a1 {
color: black;
padding: 5px;
background: cyan;
}
mark.a2 {
color: black;
padding: 5px;
background: red;
}
mark.a3 {
color: white;
padding: 5px;
background: green;
}
mark.a4 {
color: black;
padding: 5px;
background: pink;
}
</style>
</head>
<body style="border:4px solid rgb(0, 128, 28);">
<h1 style="font-family: 'Roboto Slab',
serif;text-align: center;color:green;">
GeeksForGeeks
</h1>
<br><br>
<form>
<div class="container-fluid" align="center">
<input type="text" size="30"
placeholder="search..." id="searched"
style="border: 1px solid green;
width:300px;height:30px;">
<button type="button" class="btn-primary btn-sm"
style="margin-left:-5px;height:32px;width:35px;
background-color:rgb(12, 138, 12);
border:0px;" onclick="highlight('0');">
<i class="fa fa-search"></i>
</button>
</div>
</form>
<br><br>
<div align="center">
<div>
<b><i>Choose the color of highlighter:</i></b>
</div>
<br>
<div style="background-color: cyan;
width: 20px; height: 20px;
display: inline-block; margin-left: -30px;"
onmouseover="highlight('1')">
</div>
<div style="background-color: red;
width: 20px; height: 20px;
display: inline-block; margin-left: 10px;"
onmouseover="highlight('2')">
</div>
<div style="background-color: green;
width: 20px; height: 20px;
display: inline-block; margin-left: 10px;"
onmouseover="highlight('3')">
</div>
<div style="background-color: pink;
width: 20px; height: 20px;
display: inline-block; margin-left: 10px;"
onmouseover="highlight('4')">
</div>
</div>
<div class="container-fluid" style=
"padding-left: 30%; padding-right: 30%;
padding-top: 5%;">
<p class="select">
GeeksforGeeks.org was created with a
goal in mind to provide well written,
well thought and well explained solutions
for selected questions.The core team of
five super geeks constituting of technology
lovers and computer science enthusiasts
have been constantly working in this
direction.
</p>
</div>
<script>
function highlight(param) {
// Select the whole paragraph
var ob = new Mark(document.querySelector(".select"));
// First unmark the highlighted word or letter
ob.unmark();
// Highlight letter or word
ob.mark(
document.getElementById("searched").value,
{ className: 'a' + param }
);
}
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
HTML Tutorial HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read