How do I set a data attribute without adding a value in jQuery? I want this:
JavaScript
x
2
1
<body data-body>
2
I tried:
JavaScript
1
3
1
$('body').attr('data-body'); // this is a getter, not working
2
$('body').attr('data-body', null); // not adding anything
3
Everything else seems to add the second arguments as a string. Is it possible to just set an attribute without value?
Advertisement
Answer
The attr()
function is also a setter function. You can just pass it an empty string.
JavaScript
1
2
1
$('body').attr('data-body','');
2
An empty string will simply create the attribute with no value.
JavaScript
1
2
1
<body data-body>
2
Reference – http://api.jquery.com/attr/#attr-attributeName-value
attr( attributeName , value )