Check if an Element is a Checkbox using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 10, 2022

banner

Photo from Unsplash

Check if an Element is a Checkbox using JavaScript #

To check if an element is a checkbox:

  1. Use the tagName property to check if the value is an input element.
  2. Verify that the type property on the element has a value of checkbox.
  3. If both conditions are met, the element is a checkbox.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div> <input type="checkbox" id="subscribe" name="subscribe" /> <label for="subscribe">Subscribe</label> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const checkbox = document.getElementById('subscribe'); if ( checkbox.tagName.toLowerCase() === 'input' && checkbox.getAttribute('type') === 'checkbox' ) { console.log('✅ element is a checkbox'); } else { console.log('⛔️ element is not a checkbox'); }

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 a span element, the tagName property would return "SPAN".

index.js
const checkbox = document.getElementById('subscribe'); console.log(checkbox); // 👉️ "INPUT"

This is why we used the String.toLowerCase method to convert the result to lowercase.

We used the logical AND (&&) operator, which means that both conditions have to be met for the if block to run.

The getAttribute method returns the value of the provided attribute on the element.

If the attribute does not exist on the element, the method returns null or empty string, depending on the browser's implementation.

If you need to make sure that the value stored in the checkbox variable is not null or undefined, use the optional chaining (?.) operator.

index.js
const checkbox = null; if ( checkbox?.tagName?.toLowerCase() === 'input' && checkbox?.getAttribute('type') === 'checkbox' ) { console.log('✅ element is a checkbox'); } else { console.log('⛔️ element is not a checkbox'); }
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.

The checkbox variable stores a null value in the example, therefore the else block is run.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.