We can use the tagName
property and type attribute of the DOM element to check if the DOM element is input or not.
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
The code below demonstrates how to check if the DOM element is a text input.
In the HTML tab, we created four DOM elements:
div
element with id=content
.input
element of type text
with id=input_text
.input
element of type color
with id=input_color
.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.