Is one of these more preferable than the other? Why? How about performance--if these are being called thousands of times?
A) element.setAttribute("disabled", true);
B) element.disabled = true;
They both seem to disable an input[text] element in FF 4.
In general…
Use properties. For a long time (until version 7 or 8 IIRC) Internet Explorer had a seriously broken implementation of setAttribute
that would set the property not the attribute (the classic point of failure was class
since there is no class
property (it is className
).
In this case in particular… element.setAttribute("disabled", true);
is wrong. It should be element.setAttribute("disabled", "disabled");
element.setAttribute("disabled", some_bool)
doesn't work like you'd think it will. In particular, standardswise, disabled
is what's known as a boolean attribute; its very presence, regardless of its value, makes it true. disabled=""
, disabled="disabled"
, disabled="true"
and even disabled="false"
(!!!) all mean the same thing in most browsers. (Although the last two are actually invalid HTML, most browsers will consider them equivalent to disabled="disabled"
for truth purposes. Including every one of the Big Four.) You set a boolean attribute to true by setting a value -- any value, even if it's falsy -- and you set it to false by removing the attribute entirely.
If you care about the actual string value of the attribute (which in this case you shouldn't), and particularly if the attribute isn't already exposed via the DOM (that is, it doesn't have a corresponding property), then use (get/set)Attribute
. In most cases (particularly if you care about how it affects the element, like in this case where you're trying to disable an element), use the DOM property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With