3

In javascript, is what is the difference between setting an HTMLElement property with assignment as versus using setAttribute(). The following is from a chrome session, leading me to believe there is a difference:

> i = document.createElement('input');
<input>
> i.value = 'abc';
"abc"
> i
<input>​
> i.setAttribute('value','abc');
undefined
> i
<input value=​"abc">

What exactly is the difference? Is it the type of thing that bytes you in the ass?


answer right on.

chrome displays attributes, so this led to my confusion.

cc young
  • 18,939
  • 31
  • 90
  • 148
  • Although the question is about jQuery, the answer can be applied here too: http://stackoverflow.com/questions/5874652/prop-vs-attr – Felix Kling Jul 23 '11 at 11:32
  • The reason you see the `undefined`" here is merely that that is what element.setAttribute() returns as a value. The line above `i.value = 'abc';` prints `"abc"` simply because that is the value of the assignment expression. Neither output has anything to do with what actually happened to the DOM. –  Jun 29 '12 at 09:04

1 Answers1

7

In javascript, is what is the difference between setting an HTMLElement property with assignment as versus using setAttribute()

It depends on the property.

The value property reflects the current value, the value attribute reflects the default value.

Some properties map directly onto attributes.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • are you implying that if only setAttribute() is used, when `input` is rendered, there would be no `value`? – cc young Jul 23 '11 at 10:36
  • on further testing, "default" is absolutely the correct description. if setAttribute, will set `value` if and only if `value` is undefined. – cc young Jul 23 '11 at 11:01