function highlightOnLoad() {
// Get search string
var searchString = 'test'
// Starting node, parent to all nodes you want to search
var textContainerNode = document.getElementById("content");
// Informational message for search
var searchInfo = 'Search Results for: ';
// Split search terms on '|' and iterate over resulting array
var searchTerms = searchString.split('|');
for (var i in searchTerms) {
// The regex is the secret, it prevents text within tag declarations to be affected
var regex = new RegExp(">([^<]*)?("+searchTerms[i]+")([^>]*)?<","ig");
highlightTextNodes(textContainerNode, regex, i);
// Add to info-string
searchInfo += ' <span class="highlighted term'+i+'">'+searchTerms[i]+'</span> ';
}
// Create div describing the search
var searchTermDiv = document.createElement("H2");
searchTermDiv.className = 'searchterms';
searchTermDiv.innerHTML = searchInfo;
// Insert as very first child in searched node
textContainerNode.insertBefore(searchTermDiv, textContainerNode.childNodes[0]);
}
function highlightTextNodes(element, regex, termid) {
var tempinnerHTML = element.innerHTML;
// Do regex replace
// Inject span with class of 'highlighted termX' for google style highlighting
element.innerHTML = tempinnerHTML.replace(regex,'>$1<span class="highlighted term'+termid+'">$2</span>$3<');
}
highlightOnLoad();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.