How do I set a data attribute without adding a value in jQuery? I want this:
$('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?
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.
attr( attributeName , value )
var body = document.getElementsByTagName('body'); body.setAttribute("data-body","");
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
You can do it without jQuery!
<button>My disabled button!</button>
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:
This will add the attribute in all lowercase without a value or remove it if it already exists on the element.
©2020 All rights reserved.