Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
dom
communitycreator
html

How to check if the DOM element is a text input in JavaScript

Programming Bytes

Overview

We can use the tagName property and type attribute of the DOM element to check if the DOM element is input or not.

  • For the input DOM element, the tagName is INPUT.

The valid input type to a text input can be the following:

  • text
  • password
  • number
  • email
  • tel
  • url
  • search
  • date
  • datetime
  • datetime-local
  • time
  • month
  • week

Example

The code below demonstrates how to check if the DOM element is a text input.

Console
Check if the DOM element is text input

Explanation

In the HTML tab, we created four DOM elements:

  • Line 5: We create a div element with id=content.
  • Line 6: We create an input element of type text with id=input_text.
  • Line 7: We create an input element of type color with id=input_color.
  • Line 8: We create an input element of type button with id =input_button.

In the JavaScript tab:

  • Lines 1–4: We use the getElementById() method to get the elements and store them in the variable.

  • Lines 6–14: We create a function isTextInput to check if the element is text input or not. This method will check two cases: If the element is input and if the type of the element is valid text input.

  • Line 16: We call the isTextInput with div element as an argument and return false because the div element is not text input.

  • Line 17: We call the isTextInput with input element of type color as an argument. We will get false because the input color element is not a valid text input element.

  • Line 18: We call isTextInput with input element of type text as an argument. We’ll get true as a result.

  • Line 19: We call isTextInput with input element of type button as an argument. We’ll get false because the input button element is not a valid text input element.

RELATED TAGS

javascript
dom
communitycreator
html
RELATED COURSES

View all Courses

Keep Exploring