How to check if object is a textbox with JavaScript?

Sometimes, we want to check if object is a textbox with JavaScript.

In this article, we’ll look at how to check if object is a textbox with JavaScript.

How to check if object is a textbox with JavaScript?

To check if object is a textbox with JavaScript, we can check if the object is an instance of HTMLInputElement and that its type property is set to 'text'.

For instance, we write:

<input>

to add an input element.

Then we can select it and check if it’s a textbox by writing:

const obj = document.querySelector('input')
const isInputText = obj instanceof HTMLInputElement && obj.type === 'text';
console.log(isInputText)

We select the element with document.querySelector.

Then we use the instanceof operator to check that it’s an instance of HTMLInputElement.

And then we make sure that its type attribute is set to text with obj.type === 'text'.

Therefore the console log should log true.

Conclusion

To check if object is a textbox with JavaScript, we can check if the object is an instance of HTMLInputElement and that its type property is set to 'text'.