title: How to find and replace a string in HTML DOM element using javascript
body: <p>I've tried to replace occurences of string <code>&quot;blue&quot;</code> with <code>&quot;red&quot;</code> in the document using DOM methods. However, I have not got the desired result.</p>
  <p>Here's the code I've tried:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;html&gt;
    &lt;body&gt;
      &lt;p&gt;Click the button to replace &quot;blue&quot; with &quot;red&quot; in the paragraph below:&lt;/p&gt;
      &lt;div id=&quot;main&quot;&gt;
        &lt;p&gt;Mr Blue has a blue house and a blue car.&lt;/p&gt;
        &lt;p&gt;Mr Blue has a blue house and a blue car.&lt;/p&gt;
      &lt;/div&gt;
      &lt;button onclick=&quot;myFunction()&quot;&gt;Try it&lt;/button&gt;
      &lt;script&gt;
        function myFunction() {
          var str = document.getElementById(&quot;main&quot;);
          var x = str.document.getElementsByTagName(&quot;p&quot;);
          var res = x.innerHTML.replace(/blue/gi, &quot;red&quot;);
          document.getElementsByTagName(&quot;p&quot;).innerHTML = res;
        }
      &lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>