-2

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?

  • 3
    i mean, other than the missing `$`? before `("body")`? – Kevin B Apr 11 '22 at 21:19
  • What happens when you replace terms like RAM, ROM, etc...? – Lee Taylor Apr 11 '22 at 21:20
  • 1
    Do note that this kind of replacement isn't... great. Certainly not something that you'd want to use on large blocks of html. Ideally any kind of replacement like this should occur on input, rather than on display. Or at minimum, before it's added to the dom. – Kevin B Apr 11 '22 at 21:23

1 Answers1

0

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