Reputation: 436
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?
Upvotes: 6
Views: 1200
Reputation: 1583
In JavaScript there is a way to write a code similar to object oriented design. If you wonder, you can search as JavaScript prototype; (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript)
HTMLInputElement's parent is HTMLElement;
For example, __proto__: HTMLElement
HTMLElement's parent is Element:
__proto__: Element
Upvotes: 1
Reputation: 234
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.
Upvotes: 2
Reputation: 944442
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 Node
s 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.
Upvotes: 9