Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>After some try-and-fail, I made a working demo that may be more complicated than you might have think:</p> <p><a href="http://jsfiddle.net/4VKNk/" rel="nofollow">http://jsfiddle.net/4VKNk/</a></p> <pre><code>var cache=[]; var reg=/idm/gi; var id=function(ID){return document.getElementById(ID);} function walkElement(ele){ if(ele.childNodes.length&gt;0){ for(var i=0;i&lt;ele.childNodes.length;i++){ walkElement(ele.childNodes[i]); } }else if(ele.nodeType==3){//text node if(reg.test(ele.nodeValue)){ cache.push(ele); } } } id("test").onclick=function(){ cache=[]; walkElement(id("SR")); while(cache.length&gt;0){ var ele=cache.shift(); var val=ele.nodeValue; var pnt=ele.parentNode; var nextSibling=ele.nextSibling; var i=0; var r,tmp; pnt.removeChild(ele); while(r=reg.exec(val)){ tmp=document.createTextNode(val.substring(i,r.index)); if(nextSibling){ pnt.insertBefore(tmp,nextSibling); tmp=document.createElement("strong"); tmp.appendChild(document.createTextNode("idm")); pnt.insertBefore(tmp,nextSibling); }else{ pnt.appendChild(tmp); tmp=document.createElement("strong"); tmp.appendChild(document.createTextNode("idm")); pnt.appendChild(tmp); } i=reg.lastIndex; } if(i&lt;val.length-1){ tmp=document.createTextNode(val.substring(i,val.length)); if(nextSibling){ pnt.insertBefore(tmp,nextSibling); }else{ pnt.appendChild(tmp); } } } }; </code></pre> <p>I took the approach of DOM manipulation.</p> <p>Explanation:</p> <ol> <li>Walk through the whole DOM tree under target element, and cache all TEXT_NODE (<code>nodeType==3</code>);</li> <li>Use <code>RegExp.exec()</code> method to get the index of each match;</li> <li>While you find a match, add back the text that come before it, and then add a highlight element (<code>&lt;strong&gt;</code>) that contains the match; continue this step;</li> <li>If we still have text left, add it back.</li> </ol> <p>The reason I need to cache the TEXT_NODEs first, is that if we directly modify it in <code>walkElement</code>, it will change <code>childNodes.length</code> of its parent, and break the process.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload