Set an Attribute without a Value using JavaScript

avatar

Borislav Hadzhiev

Thu Dec 30 20212 min read

Set an Attribute without a Value using JavaScript #

To set an attribute without a value, select the element and call the setAttribute() method on it, e.g. button.setAttribute('disabled', ''). If we pass an empty string as a second parameter to the setAttribute method, the attribute is set without a value.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Button</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const button = document.getElementById('btn'); button.setAttribute('data-id', ''); button.setAttribute('disabled', '');

We selected the element using the document.getElementById() method.

We then used the setAttribute method to set an attribute on the element without a value.

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 you need to remove an attribute you can use the removeAttribute method.

index.js
const button = document.getElementById('btn'); button.setAttribute('data-id', ''); button.setAttribute('disabled', ''); // ๐Ÿ‘‡๏ธ Remove attribute button.removeAttribute('disabled');

If you inspect the element, you'll see that by setting an attribute to an empty string the attribute gets set without a value.

Note that you can only call the setAttribute method on DOM elements, so if you have a collection of elements, you have to iterate over the collection and call the method on each individual element.

Here is the HTML for the next example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button class="btn">Button</button> <button class="btn">Button</button> <button class="btn">Button</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const buttons = document.querySelectorAll('.btn'); for (const button of buttons) { button.setAttribute('data-id', ''); button.setAttribute('disabled', ''); }

We used the document.querySelectorAll method to select all elements with a class of btn.

We used the for...of loop to iterate over the collection and set an attribute without a value on each element.

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