Free text search
Here's an example of how you can search for a specific keyword on a webpage using JavaScript and highlight the results:
document.addEventListener('DOMContentLoaded', function () {
const searchButton = document.getElementById('searchButton');
searchButton.addEventListener('click', searchAndHighlight);
},false);
function searchAndHighlight(e) {
e.preventDefault();
const keyword = document.getElementById('searchInput').value.trim();
// If the search input is empty, remove existing highlighting and return
if (keyword === '') {
removeHighlighting();
return;
}
const regex = new RegExp(keyword, 'gi');
// Get all text nodes within the document body
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
const textNodesToHighlight = [];
// Iterate through each text node and collect the ones that match the search keyword
while (walker.nextNode()) {
const currentNode = walker.currentNode;
if (regex.test(currentNode.textContent)) {
textNodesToHighlight.push(currentNode);
}
}
removeHighlighting();
// Apply highlighting to the matching text nodes
textNodesToHighlight.forEach(function (node) {
const span = document.createElement('span');
span.classList.add('highlight');
span.textContent = node.textContent;
node.parentNode.replaceChild(span, node);
});
// Scroll to the first highlighted occurrence
const firstHighlightedElement = document.querySelector('.highlight');
if (firstHighlightedElement) {
firstHighlightedElement.scrollIntoView({ behavior: 'smooth' });
}
}
function removeHighlighting() {
const highlightedElements = document.querySelectorAll('.highlight');
highlightedElements.forEach(function (element) {
element.outerHTML = element.textContent;
});
}
In this example, we have a webpage with a paragraph of text and an input field where you can enter a keyword to search for. When you click the "Search" button, the searchAndHighlight JavaScript function is triggered.
The function retrieves the keyword from the input field, creates a regular expression with the keyword, and retrieves the content element where the search will be performed. It then removes any previous highlighting by using a regular expression and replaces it with the original text.
Finally, it performs the search using the regular expression and adds the <span class="highlight">
tags around the matching results to apply the highlighting effect.
Note that this example provides a basic implementation for illustrative purposes. In a real-world scenario, you might want to handle edge cases, handle case sensitivity, or provide more advanced search features.