JavaScript is the backbone of every website. It helps to manage user events and also handles browser operations.
Sometimes we need to change the text of an element dynamically via user event like OnClick or OnHover event. At that time JavaScript and JQuery come in the role to handle the event.
Index
JavaScript Change Text on Click
Here we are going to see how we can change the text of an element using JavaScript function with various examples.
JavaScript uses the innerHTML property to change the text of an element.
Syntax
document.getElementById(‘id_name’).innerHTML = “new_text”;
Explanation
- Here id_name is the id of the HTML tag which you want to select.
- innerHTML is used to change the text inside the selected HTML tag using the document.getElementById() method.
- new_text is the text which we want to insert.
Example 1
Suppose we have one sample paragraph. We want to change the text of that paragraph when we click the button.
Let’s see how it can be performed.
<!DOCTYPE html> <html> <body> <p>When you click a button it will change the text of 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>
Output
Before clicking the button :
After clicking the button:
Explanation
- First we create the change_text() function.
- Then we add document.getElementById(“demo”).innerHTML inside function and add text which we want to show.
- Then after we create <p> tag and a button.
- Finally, when we click the button, it will change the text of the <p> tag.
Example 2
Suppose we want to create a form that takes the name as input field and it will show greeting message inside <p> tag. Let’s see how it can be performed.
<!DOCTYPE html> <html> <body> <p>Click the button to display greeting.</p> <p id="demo"></p> Name:<br><br> <input type="text" id="name" name="name"> <br><br> <button onclick="change_text()">Submit</button> <script> function change_text(){ var name = document.getElementById("name").value; document.getElementById("demo").innerHTML = "Hello " + name; } </script> </body> </html>
Output
Before clicking the button:
After clicking the button:
Explanation
- First, we create the change_text() function.
- Then we get the value of document.getElementById(“name”).innerHTML inside function and
Assign it to name variable. - Then after we assign the value of name variable inside the <p> tag using document.getElementById(“demo”).innerHTML.
- Finally, when we click the button, it will show the greeting text inside the <p> tag.
Read Also: How to Get URL Parameters Using JavaScript
Conclusion
This is all about how to change the text using JavaScript. I am sure you have no dought about adding text using JavaScript.
I hope you found this post informative.
Thanks for reading 🙂