JavaScript:替换网页上的某些单词



我在处理chrome扩展的一些代码时遇到了问题。该代码应该将一个单词替换为另一个单词。然而,它会这样做,我只希望它在某些标签(如<p></p>或header标签(中替换一个单词。此时,它将替换<body></body>中HTML文件中的所有单词。这有时会干扰HTML代码,并可能破坏网站的某些功能。这是我目前拥有的。

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

谢谢你的帮助!

因此,只需在您关心的所有元素上循环,并仅对这些元素进行替换。

// 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>

最新更新