0

I have to add a registered trademark symbol to all references to a brand, let's call it "SomeBrand" on a client site. Currently I have this:

function updateSomeBrand(){
  var elements = document.getElementsByTagName('*');
  for(el in elements){
    if(["SCRIPT", "META", "HEAD", "STYLE", "IFRAME", "NOSCRIPT", "IMG"].indexOf(elements[el].tagName) < 0){
      if(elements[el].innerText != undefined && elements[el].innerText.indexOf("SomeBrand") > 0){
        console.log(elements[el].innerText);
        console.log(elements[el].innerText.indexOf("SomeBrand"));
        elements[el].innerHTML = elements[el].innerHTML.replace("SomeBrand", "SomeBrand®")
      }
    }
  }
}

But it adds extra ® symbols after all references to SomeBrand, in some cases it adds six or seven. I'm not sure yet why. Is there a better way to go about this? There are a lot of references on different product pages, so I'd like to add some JS to the product page template instead of manually updating them.

Jake 1986
  • 582
  • 1
  • 6
  • 25

1 Answers1

0

You're calling .replace() in all elements, including container elements. That means that you first replace all of the HTML in the container, then replace it again for each child.

Instead, you should modify text nodes only. getElementsByTagName() equivalent for textNodes

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964