lamplightdev

How to use boolean attributes in Web Components

While all HTML attributes are strings, by reason of HTML being a plain text format, you will often hear about boolean attributes - but how do you set boolean attributes if all attributes are strings?

Declaring boolean attributes

The truth is boolean attributes don't exist on Custom Elements - when people talk about them they are referring to a simple convention: if an attribute exists on an element then it's true, whilst if the attribute doesn't exist on an element then it's false:

<!-- a boolean attribute, open, set to true-->
<my-component open></my-component>

<!-- a boolean attribute, open, set to false-->
<my-component></my-component>

Managing boolean attributes in code

There is no dedicated DOM API to deal with boolean attributes since they are a convention rather than a dedicated type of attribute, so you the use standard attribute methods.

To set a boolean attribute to true you set it to an empty string:

const el = document.querySelector('my-component');

el.setAttribute('open', '');
/*
setting an empty string will set the
attribute with no value on the element
*/

and to remove a boolean attribute to false you remove it:

el.removeAttribute('open');

To read a boolean attribute you can check it exists:

const isOpen = el.hasAttribute('open');

There's a few points to note here:

  1. You can see here that when using hasAttribute there is no requirement for the attribute to be set to an empty string - setting an attribute to any value will return true, but again by convention boolean attributes should use an empty string.

  2. It's also important to realise that the strings "true" and "false" have no dedicated meaning with HTML attributes and setting a boolean attribute to either "true" or "false" will make the boolean attribute true.

  3. There is no explicit way to set a boolean attribute to false, it must be removed. getAttribute returns null for non existent attributes, but you cannot setAttribute('open', null) - this will result in open="null" which will then be considered true.


Get the latest Web Component news, tips and advice

I send out a regular newsletter - Web Component Bytes - containing curated news, tips and advice about Web Components.

Sign up below to get it hand delivered to your inbox - no spam, and unsubscribe at anytime.