为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

子衿沉夜 2021-10-21 15:01:00
我有一些列出单词行的 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>
查看完整描述

2 回答

?
慕哥6287543

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>


查看完整回答
反对 回复 2021-10-21
?
30秒到达战场

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>


查看完整回答
反对 回复 2021-10-21
  • 2 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信