How to add a boolean attribute to an element using JavaScript?

Sometimes, we want to add a boolean attribute to an element using JavaScript.

In this article, we’ll look at how to add a boolean attribute to an element using JavaScript.

How to add a boolean attribute to an element using JavaScript?

To add a boolean attribute to an element using JavaScript, we can call setAttribute to set the boolean attribute to the same value as the attribute name to add the attribute.

We can use removeAttribute to remove the attribute.

For instance, we write:

<input>

to add an input.

Then we write:

const input = document.querySelector('input')
input.setAttribute('disabled', 'disabled');

setTimeout(() => {
  input.removeAttribute('disabled');
}, 3000)

to select the input with querySelector.

Then we call input.setAttribute with 'disabled' and 'disabled' to set the disabled attribute to disabled.

And then we call input.removeAttribute with 'disabled' in the setTimeout callback to remove the attribute in 3 seconds.

Conclusion

To add a boolean attribute to an element using JavaScript, we can call setAttribute to set the boolean attribute to the same value as the attribute name to add the attribute.

We can use removeAttribute to remove the attribute.