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

  • In Chrome, using both dataset and setAttribute lets you pass an empty string and it won't add a value.

    const test = document.querySelector("#test")
    test.dataset.testa = "";
    test.setAttribute("data-testB","");
    console.log(test)
    <div id="test">TEST</div>