Categories
JavaScript Answers

How to check if object is a textbox with JavaScript?

Spread the love

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'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *