Search code examples
javascripthasownproperty

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


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:


Solution

  • "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">