Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

javascript - What is happening behind .setAttribute vs .attribute=?

Description:

I am using simple javascript to set a the value of an input. I am using multiple methods that appear to be the same but with different results. Here is an example:

HTML:

<input name="testinput" value="" type="text" />

Javascript:

var input = document.getElementByTagName('input')[0];
input.value = "5"

console.log(input.value) // returns "5"
console.log(input.getAttribute("value")) // returns ""

Of course the functionality is reversed when using the setAttribute() function. Yet, when on form submit they both give a input=5 result.

Question:

What is the point of separating the two properties? is the .value stored differently than the .getAttribute("value")?

Disclaimer:

I have read:

Both of those question/answers left me confused and unsatisfied.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

input.value is dot notation, it sets the value property of the input object.

It does in no way update any attributes, so trying to get an attribute with the same name will not return the updated value.

If for some reason you have to update the attribute, you would do

input.setAttribute('value', 'new_value');

but you shouldn't have to use that, as you generally should be working with the properties, not the attributes, and you'd set and get the value property, not the attribute.


An attribute in HTML is a key / value pair inside the opening and closing brackets, as in

<div attribute="attribute_value"></div>

In many cases such attributes will set the initial value of the underlying property, and the property is a named key with a value, that is attached to the internal model of an element, which is what we access with javascript, the object holding the model and data for the element.

Changing any of that objects keys or values does not change the HTML, only the internal representation of the element, the object. However, changing the HTML attributes will in some cases change the object representation of the element.

getAttribute gets the actual attributes from the HTML, not the properties, while element.value clearly accesses a named property in the object representing that element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...