use*_*743 0 html javascript dom
我试图替换字符串的出现次数"blue"与"red"使用DOM方法在文档中。但是,我没有得到想要的结果。
这是我试过的代码:
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<div id="main">
<p>Mr Blue has a blue house and a blue car.</p>
<p>Mr Blue has a blue house and a blue car.</p>
</div>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = document.getElementById("main");
var x = str.document.getElementsByTagName("p");
var res = x.innerHTML.replace(/blue/gi, "red");
document.getElementsByTagName("p").innerHTML = res;
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您的代码中有多个问题。
要从 中获取ps div,您需要:
str.getElementsByTagName("p"); // and not str.document...
Run Code Online (Sandbox Code Playgroud)
上面的语句将返回一个集合而不是单个元素。所以你需要遍历集合并进行替换。
for (var i = 0; i < x.length; i++) {
var res = x[i].innerHTML.replace(/blue/gi, "red");
x[i].innerHTML = res;
}
Run Code Online (Sandbox Code Playgroud)
工作示例。
根据您的评论进行更新(什么是循环):请使用此处的教程开始。