I am iterating over each text node, and looking for a search string whether it is available in that text node or not. If it's present I will wrap around the span node to do the highlighting. The sample code is available at this link: .http://jsfiddle.net/LcRDz/.

Right now if a user gives a word, it will search only that word. I need to search the DOM for the words irrespective of case. For example if my search word is the, it should highlight the words The, THE, the.

有帮助吗?

解决方案

Before the check with indexOf use toLowercase on both values, making the comparison case insensitive.

 //Notice both n.nodeValue and word are sent to lowercase.
 for (var i;
        (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; 
           n = after) {
             var after = n.splitText(i + word.length);
             var highlighted = n.splitText(i);
             var span = document.createElement('span');
             span.className = "spanClass";
             span.style.backgroundColor = "red";
             span.appendChild(highlighted);
             after.parentNode.insertBefore(span, after);
         }

JS FIDDLE: http://jsfiddle.net/LcRDz/2/

其他提示

You should solve just by modifing

for (var i;
    (i = n.nodeValue.indexOf(word, i)) > -1; n = after) 

with

for (var i;
    (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; n = after) 

Change your for loop in highlightWords method from

Original:

for (var i;
             (i = n.nodeValue.indexOf(word, i)) > -1; n = after)

New:

for (var i;
             (i = n.nodeValue.toLowerCase().indexOf(word.toLowerCase(), i)) > -1; n = after)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top