Skip to content

Change Text in p tag JavaScript | Easy HTML example code

  • by

Find the element by id and use the innerText attribute to Change Text in p tag in JavaScript. By this approach, you can change the text dynamically based on the conditions.

Example Change Text in p tag JavaScript

HTML example code change p tag text even it’s inside a div tag in JS.

<!DOCTYPE html>
<html>
<body>

    <div
    class='container'>
    <p id='replace-me'> Hello Wrold!</p>
</div>


<script>
    document.getElementById('replace-me').innerText = "Bye...Everyone!"

</script>
</body>

</html>

Output:

HTML Example Change Text in p tag JavaScript

Q: How to change the text inside <p> onClick ?

Answer: Same as above example with using a code inside the function. The function will Tigger on clicking a button.

<!DOCTYPE html>
<html>
<body>

    <p>Sample paragraph.</p>

    <p id="demo">I am sample paragraph.</p>

    <button onclick="change_text()">Click me</button>

    <script>
        function change_text(){
            document.getElementById("demo").innerHTML = "You clicked the button, I am new paragraph.";
        }
    </script>

</body>
</html>

Explanation

  • Here id_name is the id of the HTML tag to identify it.
  • innerHTML is used to change the text inside the selected HTML tag using the document.getElementById() method.
  • change_text() is function name.

Do comment if you have any doubts and suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading