2 回答
TA贡献1831条经验 获得超10个赞
因此,使用 querySelectorAll 选择所有元素,循环并替换文本。
function myFunction() {
document.querySelectorAll(".second") // select the elements
.forEach(elem => // loop over
elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text
)
}
myFunction()
/* without the fat arrow
function myFunction() {
document.querySelectorAll(".second") // select the elements
.forEach(function(elem) { // loop over
elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text
})
}
*/
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<button onclick="myFunction()">Replace</button>
TA贡献1828条经验 获得超6个赞
您可以通过 className 选择元素,然后替换值
function myFunction() {
let elements = document.getElementsByClassName("second");
[...elements].forEach(element => {
element.innerText = element.innerText.replace(/Five/g, 'Zero')
})
}
<html>
<body>
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<p class="second">Three Four Five Six Seven</p>
<p class="third">Five Six Seven Eight Nine</p>
<p class="second">Three Four Five Six Seven</p>
<p class="first">One Two Three Four Five</p>
<button onclick="myFunction()">Replace</button>
</body>
</html>
添加回答
举报