[Javascript] setAttribute or not?

Michael Borchers list at tridemail.de
Wed Nov 28 07:48:01 CST 2007


> On 28/11/2007, Michael Borchers <list at tridemail.de> wrote:
>> var select = document.createElement('select');
>> select.name    = 'foo';
>>
>> OR
>>
>> select.setAttribute('name', 'foo');
>
> As a general rule, I would say you should use the property bindings.
> Why? Because setAttribute is broken in iew, and compatibility is much
> better when it comes to the property bindings.
>
>> Any (dis-)advantages between those two?
>
> Between these two in particular, the difference is not important. However:
> - Most bindings are string bindings like this, and both alternatives
> are relatively safe to use.
> - Some property bindings are special. The select.style binding is a
> CSSStyleDeclaration, not a string. The select.multiple binding is a
> boolean, not a string. The select.tabIndex binding is a long, not a
> string.
> - Some properties have different names in setAttribute and in the
> property bindings, for example 'class' vs. className.
> - In iew, you need to use the (case sensitive) property name, not the
> (case insensitive) attribute name.
> - In iew, getAttribute returns the type of the property binding and
> not always a string as the DOM specifies.
> - In iew, setAttribute excepts the type of the property binding and
> not a string as the DOM specifies.
> - You cannot rely on setAttribute if you want to set one of the
> attributes that have special handling/parsing such as event handler
> attributes, the style attribute etc.
>
>> Can I set an event with the first method, like select.onchange = ...,
>> or does it only work with setAttribute?
>
> You could use the DOM0 (select.onevent=function(){}) way OR the
> DOM2Events way (addEventListener) together with the iew way
> (attachEvent). Never try to use setAttribute for event handlers,
> though.
> -- 
> David "liorean" Andersson

Thanks david, lots of good answers. I'll have to review my code now;) 




More information about the Javascript mailing list