I'm trying to dynamically replace specific words with a link within a certain HTML element using JS. I figured I'd use a simple RegEx:
var regEx = new RegExp('\\b'+text+'\\b', 'gi');
The quick'n'nasty way it to apply the RegEx replace on the context div's innerHTML
property:
context.innerHTML = context.innerHTML.replace(regEx, '<a href="#">'+text+"</a>");
The problem with this is that it also applies to, say image titles, thus breaking the layout of the page. I want it to apply only to the text of the page, if possible also excluding things like header tags and of course HTML comment and such.
So I tried something like this instead, but it doesn't seem to work at all:
function replaceText(context, regEx, replace) {
var childNodes = context.childNodes;
for (n in childNodes) {
console.log(childNodes[n].nodeName);
if (childNodes[n] instanceof Text) {
childNodes[n].textContent = childNodes[n].textContent.replace(regEx, replace);
} else if (childNodes[n] instanceof HTMLElement) {
replaceText(childNodes[n], regEx, replace);
console.log('Entering '+childNodes[n].nodeName);
} else {
console.log('Skipping '+childNodes[n].nodeName);
}
}
}
Can anyone see what I'm doing wrong, or maybe come up with a better solution? Thanks!
UPDATE:
Here's a snippet of what the contents of context
may look like:
<h4>Newton's Laws of Motion</h4>
<p><span class="inline_title">Law No.1</span>: <span class="caption">An object at rest will remain at rest, and an object in motion will continue to move at constant velocity, unless a net force is applied.</span></p>
<ul>Consequences: <li>Conservation of Momentum in both elastic and inelastic collisions</li>
<li>Conservation of kinetic energy in elastic collisions but not inelastic.</li>
<li>Conservation of angular momentum.</li>
</ul>
<h5>Equations</h5>
<p class="equation">ρ = mv</p>
<p>where ρ is the momentum, and m is the mass of an object moving at constant velocity v.</p>
and and images and stuff...
– Sean Bone Dec 22 '13 at 13:58