使用 JavaScript 查找和替换 HTML 中的单词

我有一些列出单词行的 HTML,每行都附加到一个类。


我还有一个脚本函数,它对每次出现的单词“Five”进行全局查找和替换 HTML,用单词“Zero”替换它。


但是,问题是我只想在每次出现class="second".



我如何循环遍历 HTML 中的每一行,仅对特定类进行单词替换,例如使用该getElementsByClassName()方法?


代码


行动中的单词替换示例 - https://jsfiddle.net/yb0sLhqp/


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


<script>


function myFunction() {

document.body.innerHTML = document.body.innerHTML.replace(/Five/g, 'Zero');

}


</script>


</body>

</html>


子衿沉夜
浏览 165回答 2
2回答

慕哥6287543

因此,使用 querySelectorAll 选择所有元素,循环并替换文本。function myFunction() {&nbsp; document.querySelectorAll(".second")&nbsp; // select the elements&nbsp; &nbsp; .forEach(elem => // loop over&nbsp; &nbsp; &nbsp; elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text&nbsp; &nbsp; )}myFunction()/* without the fat arrowfunction myFunction() {&nbsp; document.querySelectorAll(".second")&nbsp; // select the elements&nbsp; &nbsp; .forEach(function(elem) { // loop over&nbsp; &nbsp; &nbsp; elem.textContent = elem.textContent.replace(/Five/g, 'Zero') //replace the text&nbsp; &nbsp; })}*/<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>

30秒到达战场

您可以通过 className 选择元素,然后替换值function myFunction() {&nbsp; let elements = document.getElementsByClassName("second");&nbsp; [...elements].forEach(element => {&nbsp; &nbsp; element.innerText = element.innerText.replace(/Five/g, 'Zero')&nbsp; })}<html><body>&nbsp; <p class="first">One Two Three Four Five</p>&nbsp; <p class="second">Three Four Five Six Seven</p>&nbsp; <p class="third">Five Six Seven Eight Nine</p>&nbsp; <p class="second">Three Four Five Six Seven</p>&nbsp; <p class="first">One Two Three Four Five</p>&nbsp; <p class="second">Three Four Five Six Seven</p>&nbsp; <p class="third">Five Six Seven Eight Nine</p>&nbsp; <p class="second">Three Four Five Six Seven</p>&nbsp; <p class="first">One Two Three Four Five</p>&nbsp; <button onclick="myFunction()">Replace</button></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript