Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a property via property or setAttribute

Tags:

javascript

dom

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.

like image 271
user979672 Avatar asked Nov 05 '11 07:11

user979672


2 Answers

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");

like image 169
Quentin Avatar answered Sep 21 '22 00:09

Quentin


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.

like image 26
cHao Avatar answered Sep 19 '22 00:09

cHao