Search code examples
javascripthtmlcustom-data-attribute

Is there a way to add a blank data attribute to an element using JavaScript?


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?


Solution

  • Answer copied from https://stackoverflow.com/a/78416452/1150462 with minor adaptation

    This is impossible in HTML.

    Attributes must have a value

    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.

    Why do I see attributes with no value?

    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>.

    So what should I do?

    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/)