1

I am having trouble with some code for a chrome extension. The code is supposed to replace a word with another one. It does this, however, I would only like it to replace a word if it is within certain tags such as <p></p> or header tags. At the moment it replaces all the words in the HTML file within the <body></body>. This sometimes interferes with the HTML code and can break certain features of a website. Here's what I have currently.

document.body.innerHTML = document.body.innerHTML.replace(newRegExp("old", "g"), "new");

Thank you for the help!

Vivek Athalye
  • 2,974
  • 2
  • 23
  • 32
F.Lewis
  • 11
  • 3

1 Answers1

1

So just loop over all the elements that you care about and do the replacement on those elements only.

// Get all the elements that you care about into an array
let elements = Array.prototype.slice.call(document.querySelectorAll("p, header"));

// Loop over the items in the array
elements.forEach(function(el){
  // Do the replace on the element
  el.textContent = el.textContent.replace(/text/g, "letters");
});
<header>This is some text in a header</header>
<h1>This is some text in an h1</h1>
<div>This is some text in a div</div>
<p>This is some text in a p</p>
<div>This is some text in a div</div>
<div>This is some text in a div
   <p>This text is inside of a p with lots of text</p>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71