On Apr 8, 5:38 pm, es_ <es_uomikim@ALA_MA_KOTAop.plwrote:
Leif902 wrote:
After much searching of google, the closest I can find is highlighting
search terms... however, this is not what I wanted to do.
Does anyone know how to parse through a specific element (lets say the
innerHTML of a div) and add tags to change the styles of several
keywords?
A basic script is simple, however it becomes complex very quickly:
what do you do with words that are already wrapped in emphasis or
highlighting elements?
e.g.:
<!-- Define highligh classes -->
<style type="text/css">
.animal {color: red;}
.thing {color: blue;}
</style>
<script type="text/javascript">
// Keywords
var keywordObj = {
cat : 'animal',
dog : 'animal',
mat : 'thing',
door : 'thing'
}
function highlightKeywords(el) {
var a = el.innerHTML.split(/\b/);
var w;
for (var i=0, len=a.length; i<len; i++){
w = a[i]
// If word is a keywords, wrap in highlight span
if (w in keywordObj) {
a[i] = '<span class="' + keywordObj[w] + '">'
+ w + '<\/span>';
}
}
// Update the element's innerHTML
el.innerHTML = a.join('');
}
</script>
<button onclick="highlightKeywords(document.getElementById ('p01'),
'cat');">Higlight some words</button>
<p id="p01"onclick="alert(this.innerHTML);">The cat and the
dog went through the door to sit on their mat. The cat on
the cat:mat, the dog on the dog:mat.</p>
If you press the button multiple times, you'll see that the words are
wrapped multiple times. If you want to match cat, cats, Cat, Cats,
you have to add each one to the keywords object.
There is also an interesting post from Yann-Erwan Perio:
<URL:
http://groups.google.com.au/group/co...a8f6630c533340
>
>
For instance, I might want the words "and", "or" and "xor" to be bold
and the words "c_white", "c_red" and "c_orange" to appear as maroon...
(it's for a syntax highlighting script).
It would need to be able to take multiple lists, and if it could load
those lists from an external file that would be great, but an array is
just fine... they keywords lists I am using are quite long.
An array is less functional (how do you allocate different higlighting
for different words?) and searching an array is likely much slower
than using a object with the in operator.
[...]
function doHighlight(bodyText, searchTerm)
{
[...]
That seems long-winded. Consider:
function highlightWord1(el, word, c){
var c = c || '#ff0000';
var re = new RegExp('\\b' + word + '\\b','i');
var s = el.innerHTML;
var newS = '';
while (re(s)) {
newS += RegExp.leftContext + '<span style="color:'+c+';">'
+ RegExp.lastMatch + '<\/span>';
s = RegExp.rightContext;
}
el.innerHTML = newS + RegExp.rightContext;
}
--
Rob