Why can't "hasOwnProperty" be used on instanceof HTMLInputElement?
Asked Answered
S

1

6

I want to check if an input element is a checkbox or text type.

I know I can do this:

//Type of input..
if ( input.type === "checkbox" ) 
//Contains the property..
if ( "checked" in input ) 

But my question is: why do hasOwnProperty returns false?

I just want to use:

input.hasOwnProperty("checked")

but it returns false everytime.

Isn't input an object?
I don't think so, but typeof said it is:

typeof input // returns "object" 

So what is going on?!

Code example:

const input = document.querySelector("input")
 if ( input instanceof HTMLInputElement ) {
    console.dir(input);
    console.info(typeof input);
    console.log("with 'hasOwnProperty'",input.hasOwnProperty("checked"));
    console.log("with 'in'","checked" in input);
    console.log("with 'type'",input.type === "checkbox");
}
<input type="checkbox" />

The documentation about HTMLInputElement, only type checkbox have the property checked:

Shadrach answered 4/11, 2019 at 15:47 Comment(3)
checked is not a member of input itself; it's part of HTMLInputElement's prototype.Bibi
more specifically, it's a getter that reflects the current state of the control, rather than being a property of the particular instance of HTMLInputElement.Combustor
Related discussion: #20381739 (full disclosure: my own answer)Peripteral
B
5

"checked" in input returns true because in evaluates all enumerable properties. On the contrary, .hasOwnProperty() will return true only if the property is a member of the object itself. It returns false if it's inherited or a member of the object's prototype.

In this case, checked is a getter on the HTMLInputElement.prototype, not a member of input.

const checkbox = document.getElementById("c");
const descriptor = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked');

console.log("'checked' is property of input:", "checked" in checkbox);
console.log("'checked' is own-property of input:", checkbox.hasOwnProperty("checked"));
console.log("'checked' is member of prototype:", HTMLInputElement.prototype.hasOwnProperty("checked"));
console.log("'checked' is getter:", descriptor.get !== undefined);
<input type="checkbox" id="c">
Bibi answered 4/11, 2019 at 15:59 Comment(1)
Thank you so much Tyler, Alnitak and apsillers !!Willing

© 2022 - 2024 — McMap. All rights reserved.