I have some HTML that lists lines of words, with each line attached to a class.
I also have a script function that does a global find and replace of the HTML for every occurrence of the word “Five”, replacing it with the word “Zero”.
However, the issue is that I only want to replace “Five” with “Zero” for every occurrence where class="second".
Question
How do I cycle through each line in the HTML making word replacements for only a specific class, for instance using the getElementsByClassName() method?
Code
Example of the word replacement in action - 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>