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-->
<!-- a boolean attribute, open, set to false-->
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');
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:
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
hasAttributethere 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.
It's also important to realise that the strings
"false"have no dedicated meaning with HTML attributes and setting a boolean attribute to either
"false"will make the boolean attribute true.
There is no explicit way to set a boolean attribute to false, it must be removed.
nullfor non existent attributes, but you cannot
setAttribute('open', null)- this will result in
open="null"which will then be considered true.