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
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.
document.getElementById(‘id_name’).innerHTML = “new_text”;
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 >Output
Before clicking the button :
After clicking the button:
Explanation
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 >Output
Before clicking the button:
After clicking the button:
Explanation
Read Also: How to Get URL Parameters Using JavaScript
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 🙂
There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…
In this tutorial, I'm going to show you how to install MySQL on your computer.…
Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…
We can redirect any webpage to any other or redirect the whole domain or website…
There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…
Include files in PHP are used in appending various global or config files. We can…