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.

2
  • Although the question is about jQuery, the answer can be applied here too: stackoverflow.com/questions/5874652/prop-vs-attr Commented Jul 23, 2011 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. Commented Jun 29, 2012 at 9:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

are you implying that if only setAttribute() is used, when input is rendered, there would be no value?
on further testing, "default" is absolutely the correct description. if setAttribute, will set value if and only if value is undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.