Set attribute without value

2019-01-03 09:44发布

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?

3条回答
三岁会撩人
2楼-- · 2019-01-03 10:26

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.

$(body).prop('data-body', true)
查看更多
乱世女痞
3楼-- · 2019-01-03 10:29

Perhaps try:

var body = document.getElementsByTagName('body')[0];
body.setAttribute("data-body","");
查看更多
看我几分像从前
4楼-- · 2019-01-03 10:38

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

$('body').attr('data-body','');

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 )

查看更多
登录 后发表回答