2

Is it possible through HTML, CSS or JavaScript to create a situation where every time a word is mentioned on your site it links to the same page?

For example, the word "Test":

This is a Test paragraph. I would like the word Test to link to a specific page every time it appears.

In the above paragraph, the word "Test" would link to "test.html" every time it appears without any link html appearing around it or any manual work needed. Is this possible to do? Or, alternatively, by assigning it a div tag with a class?

For my purposes it would need to work client-side without a server.

StarDart
  • 251
  • 1
  • 10
  • 7
    Check this: http://stackoverflow.com/questions/17866866/how-to-turn-keyword-on-a-site-into-links-with-jquery – Math Jan 29 '16 at 22:57
  • Well you could hard code it, depending on how many instances of test there are. You could also just use javascript to attach anchors to all instances of the word. You should probably try coming up with your own solution first. – Wold Jan 29 '16 at 22:57
  • I need a server though for jQuery, don't I? That's not available to me. – StarDart Jan 30 '16 at 20:50

2 Answers2

1

You want to replace only text nodes, not the whole DOM, or you may incur in errors if you replace words that are valid HTML tags, such as form. This is a recursive replace that respects the HTML tags and only replaces actual text:

function walkTheDOM(node, func)
{
  func(node);
  node = node.firstChild;
  while (node)
  {
    walkTheDOM(node, func);
    node = node.nextSibling;
  }
}

function supplant(word, link)
{
    return function (node) {
        if (node.nodeType === 2) // only if the node contains actual text
        {
            node.innerHTML = node.innerHTML.replace(word, "<a href=\"" + link + ">" + word + "</a>");
        }
    };
}

You can use it as follows:

walkTheDOM(document.body, supplant("form", "https://en.wikipedia.org/wiki/Form"));
pid
  • 11,472
  • 6
  • 34
  • 63
0

A short answer based on the informations you provided could be this:

document.body.innerHTML = document.body.innerHTML.replace(/Test/g, '<a href="test.html">Test</a>');
This is a Test paragraph. I would like the word Test to link to a specific page every time it appears.
Dan Ovidiu Boncut
  • 3,083
  • 4
  • 25
  • 45