How to write a jQuery selector for the label of a checkbox?

To write a jQuery selector for the label of a checkbox, use the for attribute of the label element. The for attribute creates a connection between the label and its associated form control by matching the element's id.

Syntax

The basic syntax for selecting a checkbox label using jQuery is ?

$("label[for='checkbox-id']")

Example

You can try to run the following code to learn how to write a jQuery selector for the label of a checkbox ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("label[for='sub1']").css("background-color", "yellow");
            $("label[for='sub2']").css("background-color", "lightgray");
        });
    </script>
</head>
<body>
    <form>
        <input type="checkbox" name="filter" id="sub1"/>
        <label for="sub1">Mathematics</label><br>
        
        <input type="checkbox" name="filter" id="sub2"/>
        <label for="sub2">Science</label>
    </form>
</body>
</html>

The output of the above code is ?

The first checkbox label "Mathematics" will have a yellow background
The second checkbox label "Science" will have a light gray background

Multiple Label Selection

You can also select multiple checkbox labels at once using comma-separated selectors ?

$("label[for='checkbox1'], label[for='checkbox2']").css("color", "blue");

Conclusion

Using the label[for='element-id'] selector allows you to precisely target checkbox labels in jQuery. This method ensures proper association between labels and their corresponding checkboxes for better accessibility and styling control.

Updated on: 2026-03-13T18:14:29+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements