Hello all,
I really want help here, How to create the result page template with SearchWP.
Also would like to get the search results page with Highlight Search Terms.
Regards
Hello all,
I really want help here, How to create the result page template with SearchWP.
Also would like to get the search results page with Highlight Search Terms.
Regards
Hi @Kareem
You can add this JS Code on your results page or under the query loop element, but not within the query loop. Then you have to create a class for the styling and add the name of this class into this JS code (replace “underlined”).
document.addEventListener('DOMContentLoaded', function () {
// Retrieve the search term from the URL
const urlParams = new URLSearchParams(window.location.search);
const searchTerm = urlParams.get('s');
// If a search term exists, proceed with highlighting
if (searchTerm) {
// Select all elements where the search term might appear
const elementsToHighlight = document.querySelectorAll('.brxe-heading, .brxe-div, .brxe-block');
elementsToHighlight.forEach((element) => {
// Use a regular expression to match the search term (case-insensitive)
const regex = new RegExp(`(${searchTerm})`, 'gi');
// Replace matching text with the same text wrapped in a span with the 'underlined' class
element.innerHTML = element.innerHTML.replace(regex, '<span class="underlined">$1</span>');
});
}
});
If you’ve any questions, pls let me know
In addition to the code above, here’s a better code - you only have to change the search parameter “s” and the class “underlined”
document.addEventListener('DOMContentLoaded', function () {
// Retrieve the search term from the URL
const urlParams = new URLSearchParams(window.location.search);
const searchTerm = urlParams.get('s');
// If a search term exists, proceed with highlighting
if (searchTerm) {
// Select all text nodes in the document body
const bodyTextNodes = getTextNodes(document.body);
bodyTextNodes.forEach((node) => {
const regex = new RegExp(`(${searchTerm})`, 'gi');
if (regex.test(node.textContent)) {
// Replace matching text with the same text wrapped in a span with the 'underlined' class
const newText = node.textContent.replace(regex, '<span class="underlined">$1</span>');
const spanElement = document.createElement('span');
spanElement.innerHTML = newText;
node.parentNode.replaceChild(spanElement, node);
}
});
}
});
// Helper function to get all text nodes in the document
function getTextNodes(root) {
const nodes = [];
const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
let node;
while (node = walk.nextNode()) {
nodes.push(node);
}
return nodes;
}