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
:
checked
is not a member ofinput
itself; it's part ofHTMLInputElement
's prototype. – Bibigetter
that reflects the current state of the control, rather than being a property of the particular instance ofHTMLInputElement
. – Combustor