I’m writing a widget that searches for specific keywords in a specified “#content” div.
Here is how I set it up originally using jQuery (simplified version):
- set a variable equal to the html of the content:
var content = $('content').html(); - use some regexes to replace certain keywords with
<a href='link.html'>keyword</a> - replace the html of the content div with the new content:
$('content').html(content);
This works for the most part, but the problem occurs when the “#content” div contains javascript. When I set $('content').html(content), it re-runs any javascript code contained in the $('content') div, which can cause errors. Since this is a widget that I’m writing to work on any site, I don’t have control over the content div, and whether there will be any javascript in it.
My questions is, is there a way to replace JUST the keywords with <a href='link.html'>keyword</a>, WITHOUT replacing the entire content of the div?
Yes. It’s one of the (few) places where jQuery doesn’t really offer you much.
Down at the raw DOM API level, though, the
Textnode containing the actual text of the element has asplitTextfunction with which you can split the node into two adjacent nodes at a specific location. So in your case, you’d split at the beginning of the word and then again after the end of it, then wrap that middleTextnode in a new anchor.Here’s an example: Live copy | source
HTML:
JavaScript:
Naturally there are some things you’d want to do to improve that:
index === 0case without creating an empty text node at the beginning of the parent element. (Harmless, but less than ideal.)