Ankaj Gupta
July 24, 2020

How to overwrite text in p tag using JavaScript ?

Javascript find and replace text in html

In this post, we will learn how to change/overwrite the contents of the p tag using JavaScript, with the help of class name and id, and other. Let's see

# Method 1 : Change inner txt by using id :

  ➤ Example :

<p id="p-tag">www.coderwebsite.com</p>
<script>
   document.getElementById('p-tag').innerText = "Change Me!"
</script>

# Method 2 : Change inner txt by using a class name:

  ➤ Example :

<p class="p-tag">www.coderwebsite.com</p>
<script>
    x=document.getElementsByClassName('p-tag');  // Find the elements
    for(var i = 0; i < x.length; i++){
      x[i].innerText="Hello JavaScript!";    // Change the content
    }
</script>

# Method 3 : Change inner txt on onclick button using a class name:

  ➤ Example :

<p class="p-tag">www.coderwebsite.com</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<script>
  function myFunction(){
    x=document.getElementsByClassName('p-tag');  // Find the elements
    for(var i = 0; i < x.length; i++){
      x[i].innerText="Hello JavaScript!";    // Change the content
    }
  }
</script>
Code JavaScript Code

Join the discussion

Comments

0 comments

No comments yet — be the first to share your thoughts.

Related Posts