Determine element’s type with JavaScript/jQuery
This post will discuss how to determine the element’s type in JavaScript and jQuery.
1. Using JavaScript
The tagName property returns the element’s tag name in upper-case for HTML documents. For example, tagName returns DIV when called on a <div> element.
JS
|
1 2 |
var elementType = document.getElementById("name").tagName; alert(elementType); |
HTML
|
1 2 |
<label for="name">Email address:</label> <input type="email" id="name" placeholder="Enter email"> |
Alternatively, you can use the nodeName property that returns the current Node’s name, which is the same as tagName for an element.
JS
|
1 2 |
var elementType = document.getElementById("name").nodeName; alert(elementType); |
HTML
|
1 2 |
<label for="name">Email address:</label> <input type="email" id="name" placeholder="Enter email"> |
Note when called on an <input> element, both the tagName or nodeName property returns INPUT, which doesn’t tell whether the input is a text box or a checkbox or a radio button. However, you can use the type attribute for this purpose:
JS
|
1 2 |
var elementType = document.getElementById("name").type; alert(elementType); |
HTML
|
1 2 |
<label for="name">Email address:</label> <input type="email" id="name" placeholder="Enter email"> |
2. Using jQuery
With jQuery, you can use the .prop() method to get the value of tagName or nodeName or type property.
JS
|
1 2 3 4 |
$(document).ready(function() { var elementType = $("#name").prop('nodeName'); alert(elementType); }); |
HTML
|
1 2 |
<label for="name">Email address:</label> <input type="email" id="name" placeholder="Enter email"> |
If you just need to check for the specific type of element, you can use the .is() method, which returns a Boolean value:
JS
|
1 2 3 4 |
$(document).ready(function() { var isInput = $("#name").is("input"); alert(isInput); }); |
HTML
|
1 2 |
<label for="name">Email address:</label> <input type="email" id="name" placeholder="Enter email"> |
That’s all about checking an element’s type in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)