I want to create an element like the following with JavaScript:
<div data-boolean-attribute></div>
Passing null
or undefined
to setAttribute()
or the dataset
property results in a value of the literal strings 'null'
and 'undefined'
. Passing an empty string or array to either method results in an empty string value:
<div data-boolean-attribute=""></div>
Is it possible to create a completely empty data attribute in vanilla JavaScript without using something like innerHTML
?
Answer copied from https://stackoverflow.com/a/78416452/1150462 with minor adaptation
This is impossible in HTML.
According to the HTML standard:
Attributes have a name and a value... Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.
The reason you see an attribute without a value in HTML code is because the HTML standard states:
Empty attribute syntax
Just the attribute name.
The value is implicitly the empty string.
Therefore, <div data-boolean-attribute></div>
is simply a shortened form of <div data-boolean-attribute=""></div>
.
In modern JS, you should simply call setAttribute("data-boolean-attribute", "")
. Your browser element inspector is free to display the attribute as data-body
(Chrome) or data-body=""
(Firefox).
(Shortened and adapted from https://8hob.io/posts/set-attribute-without-value-in-js/)