Check if an Element is a Checkbox using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 10 20222 min read

banner

Photo by Matthew Henry

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 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