skip to Main Content

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


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

    const test = document.querySelector("#test")
    test.dataset.testa = "";
    test.setAttribute("data-testB","");
    console.log(test)
    <div id="test">TEST</div>
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search