Boolean HTML Attributes

爷,独闯天下 提交于 2019-11-27 08:22:45
bobince

(Because of some framework code I use, not calling setAttribute(), or calling removeAttribute() is difficult.)

Then I would submit that the framework code needs fixing, or dumping.

You can't setAttribute to unset an attribute, by design. Any solution you found involving out-of-band values like ‘null’, if it happened to work in any particular browser, would be quite invalid according to the DOM Core standard.

setAttribute() is in any case best avoided in browser (non-XML) HTML contexts. IE pre-8 doesn't know the difference between a DOM attribute and a JavaScript property, which can easily result in many really weird problems. If you're trying to set ‘checked’ as an attribute (which theoretically you should do by setting it to the string "checked"), don't expect IE to co-operate.

The full list of boolean attributes in HTML 4.01 (and hence XHTML 1.0) is (with property names where they differ in case):

checked             (input type=checkbox/radio)
selected            (option)
disabled            (input, textarea, button, select, option, optgroup)
readonly            (input type=text/password, textarea)
multiple            (select,input)
ismap     isMap     (img, input type=image)

defer               (script)
declare             (object; never used)
noresize  noResize  (frame)
nowrap    noWrap    (td, th; deprecated)
noshade   noShade   (hr; deprecated)
compact             (ul, ol, dl, menu, dir; deprecated)

Try removeAttribute:

option.removeAttribute("selected");

EDIT: After reading your comment, read this about setAttribute. Notably:

Even though getAttribute() returns null for missing attributes, you should use removeAttribute() instead of elt.setAttribute(attr, null) to remove the attribute.

on table cells e.g. TD, TH

nowrap

for the record, to change attributes like checked (on checkbox/radio elements) you can do.

myCheckBoxElem.checked = true|false;

or

myCheckBoxElem.checked = !myCheckBoxElem.checked;//toggles to the opposite state

Can't you just use removeAttribute()?

Not exactly what you're asking about, but both the 'class' and 'for' attributes receive different DOM names

element.className
element.htmlFor
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!