Check if an Element is a Select dropdown using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

banner

Photo by Drew Coffman

Check if an Element is a Select dropdown using JavaScript #

Use the tagName property to check if an element is a select dropdown, e.g. if (select.tagName === 'SELECT') {}. The tagName property returns the tag name of the element on which it was accessed. Note that the property returns tag names of DOM elements in uppercase.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <select name="fruits" id="fruit-select"> <option value="">--Choose an option--</option> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="kiwi">Kiwi</option> </select> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const select = document.getElementById('fruit-select'); if (select.tagName === 'SELECT') { console.log('โœ… element is a select dropdown'); } else { console.log('โ›”๏ธ element is not a select dropdown'); }

The tagName property returns the tag name of the element on which it was accessed.

It should be noted that DOM element names are upper-cased. For example, if accessed on an div element, the tagName property would return "DIV".
index.js
const select = document.getElementById('fruit-select'); console.log(select.tagName); // ๐Ÿ‘‰๏ธ "SELECT"

You could use the String.toLowerCase method to convert the tag name to lowercase.

index.js
const select = document.getElementById('fruit-select'); if (select.tagName.toLowerCase() === 'select') { console.log('โœ… element is a select dropdown'); } else { console.log('โ›”๏ธ element is not a select dropdown'); }
This approach is a bit more intuitive, because readers of your code might get confused by the capitalized SELECT string.

If you need to make sure that the value stored in the select variable is not null or undefined before accessing the tagName property, use optional chaining.

index.js
const select = null; if (select?.tagName?.toLowerCase() === 'select') { console.log('โœ… element is a select dropdown'); } else { console.log('โ›”๏ธ element is not a select dropdown'); }
You could get a null value back if you provide a non-existent id to the getElementById method or a non-existent selector to the querySelector method.

The optional chaining (?.) operator allows us to short-circuit if the reference points to a null or undefined value.

Instead of throwing an error, the operator short-circuits returning undefined.

In the example above, the select variable has a value of null, therefore the else block is ran.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee