How to check if the DOM element is a text input in JavaScript
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
inputDOM element, thetagNameisINPUT.
The valid input type to a text input can be the following:
textpasswordnumberemailtelurlsearchdatedatetimedatetime-localtimemonthweek
Example
The code below demonstrates how to check if the DOM element is a text input.
Explanation
In the HTML tab, we created four DOM elements:
- Line 5: We create a
divelement withid=content. - Line 6: We create an
inputelement of typetextwithid=input_text. - Line 7: We create an
inputelement of typecolorwithid=input_color. - Line 8: We create an
inputelement of typebuttonwithid =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
isTextInputto check if the element is text input or not. This method will check two cases: If the element isinputand if the type of the element is valid text input. -
Line 16: We call the
isTextInputwithdivelement as an argument and returnfalsebecause thedivelement is not text input. -
Line 17: We call the
isTextInputwithinputelement of typecoloras an argument. We will getfalsebecause theinputcolor element is not a valid text input element. -
Line 18: We call
isTextInputwithinputelement of typetextas an argument. We’ll gettrueas a result. -
Line 19: We call
isTextInputwithinputelement of typebuttonas an argument. We’ll getfalsebecause theinputbuttonelement is not a valid text input element.