문제

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