Why does document.getElementById return an object named "value"?

I am trying to learn JavaScript and the DOM. Based on some examples on the Internet, I created this HTML code:

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

Then in the JavaScript code I have this line.

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

The code works well. I can change what is shown inside this text entry. But now I'm trying to understand the basic code and how it all works. I was looking for a link to the DOM at https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById .

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

Is this code above a bit of a child? Why does the value property work as such?

+6
source share
3 answers

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

If an object is inherited from another object, it will have all the properties of this object.

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

The object must be an Element , so it can sit in the DOM tree (only Node can do this, and Element inherits from Node ). It must be an Element , so it can have an id .

Only some element types have a value property that can be useful to change, so your code should also be an HTMLInputElement (or another element type with a value property), but getElementById doesn’t worry about that.

For further reading, see Prototype Programming .

+9
source

Not sure if this is what you are looking for.

'value' is a prototype property of HTMLInputElement:

 console.log(HTMLInputElement.prototype); 

The element you returned getElementById is an instance of this prototype.

Therefore, you can control the value property.

+2
source

JavaScript has a way to write code that looks like an object-oriented design. If you're interested, you can search as a prototype of JavaScript; ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript )

The parent of the HTMLInputElement is an HTMLElement;

For example, __proto__: HTMLElement

HTMLElement element - element:

 __proto__: Element 
+1
source

Source: https://habr.com/ru/post/973941/


All Articles