I've tried to replace occurences of string "blue" with "red" in the document using DOM methods. However, I have not got the desired result.
Here's the code I've tried:
<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>
getElementsByTagNamereturns a NodeList; you need to loop.x[0].innerHTML. yes, it should be a loop. just gave an example how it can be updated...