How To Check If An Element Is A Checkbox Using Javascript?

Check if an element is a checkbox using javascript

You can creat an HTML checkbox with<input> to check if an element is a checkbox using javascript. We will talk about the specific steps in this article. Let’s check it out!

Creating an HTML checkbox with <input>

At first, we have to create an HTML checkbox by using <input> element with the attribute “type” is “checkbox” or not.

Code:

<label for="male" > 
<input type="checkbox" id="male" name="male"> Male 
</label>

Now we have an input element name “male” to check if a user is male or not. So what can we do to check if an element is a checkbox using javascript?

Check if an element is a checkbox using javascript

Use element. type method

We can use elements. Type to get the type of element we want to check. This example below will show you how it works.

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check if an element is a checkbox using javascript</title>
</head>

<body>
    <label for="male" >
        <input type="checkbox" id="male" name="male"> Male
    </label>
    
     <script>
        const checkbox = document.querySelector('#male');

        if(checkbox.type=='checkbox'){
           console.log("The type of this input is "+checkbox.type);
        };

    </script>

</body>
 
</html>

Output:

The type of this input is a checkbox

The .type method will return the type of the element into string. Now we know the type of the element is a checkbox or not.

Use matches() method

We can also use the matches() method to check the type of element is a checkbox or not by using [type= “checkbox”]. The result will return true or false to show us whether the element’s type matches the “checkbox” or not.

The example below will show you how it works.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check if an element is a checkbox using javascript</title>
</head>

<body>
    <label for="male" >
        <input type="checkbox" id="male" name="male"> Male
    </label>
    
     <script>
        const checkbox = document.querySelector('#male');

        if(checkbox.matches('[type="checkbox"]')){
           console.log("The type of this input is a checkbox");
        };

    </script>

</body>

</html>

Output:

The type of this input is a checkbox

Summary

To summarize, there are many ways to check if an element is a checkbox using javascript. After reading this article, we know some easy ways such as using the element.type or matches() method in javascript.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *