Disable an Element by ID using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

banner

Photo by Mario Scheibl

Disable an Element by ID using JavaScript #

To disable an element by id:

  1. Select the element using the document.getElementById() method.
  2. Use the setAttribute() method to set the disabled attribute on the element.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" name="first_name" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const element = document.getElementById('first_name'); // โœ… Set disabled attribute element.setAttribute('disabled', ''); // โœ… Remove disabled attribute // element.removeAttribute('disabled');

We selected the element using the document.getElementById method.

We used the setAttribute method to set the disabled attribute on the element.

The method takes the following 2 parameters:

  1. name - the name of the attribute to be set.
  2. value- the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise a new attribute is added with the specified name and value.

When setting the value of a boolean attribute, such as disabled, we can specify any value for the attribute and it will work.

If the attribute is present at all, regardless of the value, its value is considered to be true.

If a boolean attribute is not present, the value of the attribute is considered to be false.

If I load the page with the example from the code snippet, I can see that the disabled attribute is set on the element.

disabled attribute set

If you need to remove an attribute from the element, use the removeAttribute method.

index.js
const element = document.getElementById('first_name'); // โœ… Set disabled attribute element.setAttribute('disabled', ''); // โœ… Remove disabled attribute element.removeAttribute('disabled');
When setting the disabled attribute, we pass an empty string as the value for the attribute, because it's a best practice to set boolean attributes without a value.

If the attribute is not set on the element, the removeAttribute method returns without throwing an error.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee