In this tutorial we will learn How to Get Button text with JavaScript. innerHTML property, innerText property and textContent property can be used along with getElementById() method to select button tag and to get it's text.
Table of Contents
innerHTML property
innerHTML property sets or returns the HTML content of HTML tag including it's text and the tags inside it.
In this example innerHTML property is used to get the text of button tag.
innerText property
innerText property sets or returns only text content of HTML tag including the text of all it's child elements.
We can also use innerText property to get text of button.
textContent property
textContent property sets or returns text content of HTML tag including the text of it's child elements which are used for text formatting.
textContent property is also used to get text of button element.
getElementById() method
getElementById() method is used to select HTML element by it's id.
In this example getElementById() method is used to select button tag.
HTML Code
HTML Code is given below, in this code we have a HTML button with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Get Button text</title>
</head>
<body>
<button onclick="getButtonText()" id='btn' >Click Me!</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function getButtonText() will get the text of button.
Using this code you can also get the text of another button on the same page by using id of that button.
<script>
function getButtonText()
{
var button = document.getElementById('btn');
var text = button.innerHTML;
alert(text);
}
</script>
Using innerText property.
<script>
function getButtonText()
{
var button = document.getElementById('btn');
var text = button.innerText;
alert(text);
}
</script>
Using textContent property.
<script>
function getButtonText()
{
var button = document.getElementById('btn');
var text = button.textContent;
alert(text);
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Get button text using JavaScript.