How to use boolean attributes in Web Components
Thu Apr 29 2021
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:
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 returntrue
, but again by convention boolean attributes should use an empty string.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.There is no explicit way to set a boolean attribute to false, it must be removed.
getAttribute
returnsnull
for non existent attributes, but you cannotsetAttribute('open', null)
- this will result inopen="null"
which will then be considered true.