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

488 views Asked by At

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

There are 2 answers

2
imvain2 On BEST ANSWER

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>

0
hygtfrde On

Create a new div element, then set data attr to empty string, and append it to the DOM body.

const div = document.createElement('div');
div.dataset.booleanAttribute = '';
document.body.appendChild(div);