Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does document.getElementById return an object that has a property called 'value'?

Tags:

javascript

dom

I'm trying to learn JavaScript and the DOM. Based on some examples on the Internet I have created this HTML:

<input type="text" id="amount3">

Then later in the JavaScript code I have this line.

document.getElementById("amount3").value= x;

The code works well. I'm able to change what's shown inside that text input. But now I'm trying to understand the underlying code and how it all works. I looked up some DOM reference in https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById.

I can see that the method should return an object Element. However, element does not contain a property called value. But I notice there is a sub-object called HTMLElement which has a sub-object HTMLInputElement. And that object contains a property called value.

Is that code above somehow typecast as the child object? Why does the value property work as such?

like image 355
mitch Avatar asked Aug 17 '14 20:08

mitch


2 Answers

HTMLInputElement inherits from HTMLElement which, in turn, inherits from Element.

If an object inherits from another object, then it will have all the properties of that object.

This means that anything which expects to deal with an Element can be given an HTMLInputElement instead (since the HTMLInputElement has all the properties of an Element, but some extra ones too).

The object needs to be an Element so it can sit in a DOM tree (only Nodes can do that, and Element inherits from Node). It needs to be an Element so it can have an id.

Only some types of element have a value property that you can usefully change, so your code also needs it to be an HTMLInputElement (or another kind of element with a value property), but getElementById doesn't care about that.

For further reading, see Prototype-based programming.

like image 191
Quentin Avatar answered Oct 05 '22 23:10

Quentin


Not sure this is what you're looking for.

'value' is a property of the HTMLInputElement prototype:

console.log(HTMLInputElement.prototype);

The element you returned by getElementById is an instance of that prototype.

Therefore, you can manipulate its value property.

like image 45
Pagerange Avatar answered Oct 05 '22 23:10

Pagerange