David David - 5 months ago 224x
Javascript Question

Set attribute without value

How do I set a data attribute without adding a value in jQuery? I want this:

<body data-body>

I tried:

$('body').attr('data-body'); // this is a getter, not working
$('body').attr('data-body', null); // not adding anything

Everything else seems to add the second arguments as a string. Is it possible to just set an attribute without value?

Lix Lix

The attr() function is also a setter function. You can just pass it an empty string.


An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )