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
?
2
Answers
Using both dataset and setAttribute, you can pass an empty string and it won’t add a value.
This was at least tested in Chrome.
Create a new div element, then set data attr to empty string, and append it to the DOM body.