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
:
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
Then no, you don't need to use the hasOwnProperty() . But the full control over the environment is not something you should count on. It's fine to drop the hasOwnProperty() only until someone somewhere redefines the Object type. Before or even after your script is started.
"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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With