In this tutorial we will see how to Toggle Text of HTML Element with JavaScript onclick. The onclick event is used with HTML Dom id property, getElementsByName method and getElementsById method.
Table of Contents
HTML Code
HTML Code is given below, This code contains button element with onclick event and a paragraph text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Toggle Text of HTML Element with JavaScript onclick</title>
</head>
<body>
<p id="text">HowToCodeSchool.com</p>
<button name='button' id='1' onclick="changeText()">Change Text</button>
</body>
</html>
onclick Event
JavaScript Code is given below, In this code the onclick event is used to toggle the text inside paragraph element.
The onclick event occurs when an element is clicked, it is used to call a JavaScript function when click event is occurred.
In this simple example, the onclick event calls a main function, then id of button element is checked, if id is 1 then text of paragraph is changed to 'Learn Programming' and the id of button is set to 0.
On next click, the id of button will be 0, as it was changed on first click, so the lines inside else will be executed and text will change back to 'HowToCodeSchool.com'.
HTML DOM id Property, getElementsByName method and getElementById method are also used in this example.
HTML DOM id Property
The HTML DOM id Property sets or returns the id of selected html element. In this example it is used to first read the id of button element and then to change it.
getElementsByName method
The getElementsByName method returns the html element with defined value of name attribute. In this example the name is 'button'. It is used to select the button element to read it's id.
Since we are changing the id of button again and again so we can't use it to select it.
getElementById method
The getElementById method is used to select html element with specific id, in this example we are using it to select the paragraph element to change it's text.
JavaScript Code
Take a look at the code given below.
<script>
function changeText()
{
var id=document.getElementsByName("button")[0].id;
if(id==1)
{
document.getElementById("text").innerHTML = "Learn Programming";
document.getElementsByName("button")[0].id=0;
}
else
{
document.getElementById("text").innerHTML = "HowToCodeSchool.com";
document.getElementsByName("button")[0].id=1;
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Toggle Text of HTML Element with JavaScript onclick.