whether to use setElement or just set the attribute directly

J

James Black

I am curious if there is a benefit to set attributes directly, in my
javascript, or to use setAttribute.

For example, I have this:
var input = document.createElementNS(xhtmlNS, 'input');
input.setAttribute('width', '20em');

I could have just called input.width='20em'

When is each better to use, or is there no difference between them?

Thank you for any help.
 
I

Ian Collins

James said:
I am curious if there is a benefit to set attributes directly, in my
javascript, or to use setAttribute.

For example, I have this:
var input = document.createElementNS(xhtmlNS, 'input');
input.setAttribute('width', '20em');

I could have just called input.width='20em'

When is each better to use, or is there no difference between them?
Input doesn't have a width attribute, so this isn't a good example. The
first form should throw an exception while the second will add a
property 'width' to 'input'.

For attributes defined in the DOM, you are better off using the second
form. setAttribute doesn't work as expected in IE, which can cause all
kinds of problems (try setting the class of an element with setAttribute).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top