'How would I replace the first instance of a string in an HTML page?

I am a technical writer and in my job we run into a lot of content reuse. It's standard to write out the first instance like "Hypertext Markup Language (HTML)" and just use HTML from then on out. However, if I'm constantly reusing blocks of text, it is hard to do this consistently. I would like to simply write the acronym every time, and on page load, replace the first instance with the complete phrase via JS.

I tried this script that I found online, but it doesn't work and generates an error in chrome developer tools (TypeError: "body".html is not a function):

var replaced = ("body").html().replace('HTML', 'Hypertext Markup Language');
$("body").html(replaced);

Is this script wrong or am I missing something?



Solution 1:[1]

How about this:

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}

function replaceAllInPage(oldStr, newStr) {
  textNodesUnder(document.body).forEach(node => {
    node.textContent = 
      node.textContent.replaceAll(oldStr, newStr);
  });
}

replaceAllInPage('HTML', 'Hypertext Markup Language');

textNodesUnder is by Phrogz

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nitsan BenHanoch