In this tutorial we will learn How to Disable Button by Class Name with JavaScript. For this we will use getElementsByClassName() method and JavaScript disabled attribute.
Table of Contents
getElementsByClassName() method
getElementsByClassName() method returns all HTML Elements with the specified class name.
getElementsByClassName() method is read-only.
To select only one HTML element out of collection, we can use index which starts from 0.
For example, if there are more than one button with same class name then to select first button we can use [0] with getElementsByClassName() method.
Similarly, we can use [1] for the second button and so on.
Disabled Attribute
JavaScript disabled attribute is used to disable the HTML elements. It is mostly used for HTML form elements including button.
HTML Code
HTML Code is given below, in this code we have input tag to take the class name as an input from the user and a button tag with onclick event which is used to execute a JavaScript function.
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Disable Button by Class Name</title>
<style>
.red
{
color: red;
}
.green
{
color: green;
}
.blue
{
color: blue;
}
</style>
</head>
<body>
<input type="text" placeholder="Enter class of Button" id="className">
<button class="red">Red</button>
<br>
<button class="blue">Blue</button>
<br>
<button class="green">Green</button>
<br>
<button onclick="disable()">Disable</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, in this code getElementById() method is used along with value property to get the class name. This class name will be used to target the button tag.
Then getElementsByClassName(className)[0].disabled will disable the button tag with specified class name.
<script>
function disable()
{
var className = document.getElementById('className').value;
document.getElementsByClassName(className)[0].disabled=true;
}
</script>
If you want to disable more than one button tags with same class name then you can use for loop.
<script>
function disable()
{
const buttons = document.getElementsByClassName("className");
for (let i = 0; i < buttons.length; i++) {
buttons[i].disabled=true;
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on How to Disable Button by Class Name in JavaScript.