我在使用Chrome扩展程序的某些代码时遇到了麻烦。该代码应该用另一个替换一个单词。它是这样做的,但是,我只希望它替换某个单词,例如<p></p>
或标头标签中的单词。目前,它替换了<body></body>
中HTML文件中的所有单词。这有时会干扰HTML代码,并可能破坏网站的某些功能。这是我目前的情况。
document.body.innerHTML = document.body.innerHTML.replace(newRegExp("old", "g"), "new");
谢谢您的帮助!
答案 0 :(得分:1)
因此,只需遍历您关心的所有元素,然后仅对这些元素进行替换即可。
// 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>