CSS selector for a checked radio button label using JavaScript/jQuery
This post will discuss how to add a CSS selector for a label of a checked radio button or a checked checkbox using JavaScript and jQuery.
To apply a CSS style to a label of a checked radio button or a checked checkbox, you can use the :checked CSS pseudo-class selector with the adjacent sibling combinator (+).
- The :checked CSS pseudo-class selector matches any checked/selected radio button, checkbox, or option element.
- The adjacent sibling combinator takes two selectors that are children of the same parent and matches the second element if it comes immediately after the first element. It is syntax is:
first_element + second_element { style }
1. Radio Button
For a radio button, you can use the input[type="radio"]:checked + label selector, which matches a label that immediately follows a checked input of type radio.
CSS
|
1 2 3 |
input[type="radio"]:checked + label { font-weight: bold; } |
HTML
|
1 2 3 4 5 6 7 8 |
<p>Select your preferred contact method:</p> <div> <input type="radio" id="email" name="contact" value="email"> <label for="email">Email</label> <input type="radio" id="phone" name="contact" value="phone"> <label for="phone">Phone</label> </div> |
2. Check Box
For a checkbox, you can use the input[type="checkbox"]:checked + label selector, which matches with a label that immediately follows a checked input of type checkbox.
CSS
|
1 2 3 |
input[type="checkbox"]:checked + label { font-weight: bold; } |
HTML
|
1 2 3 4 5 6 7 8 9 10 |
<p>Select your preferred contact method:</p> <div> <input type="checkbox" id="email" name="contact"> <label for="email">Email</label> </div> <div> <input type="checkbox" id="phone" name="contact"> <label for="phone">Phone</label> </div> |
Alternatively, you can use the :checked + label, which matches with labels of both the radio button and a checkbox that is checked.
|
1 2 3 |
:checked + label { font-weight: bold; } |
3. Drop Down
For a dropdown, you can use the option:checked selector, which matches with the option elements that are selected.
CSS
|
1 2 3 |
option:checked { font-weight: bold; } |
HTML
|
1 2 3 4 5 6 7 |
<label for="contact">Select your preferred contact method:</label> <select name="contact" id="contact"> <option value="email">Email</option> <option value="phone">Phone</option> <option value="mail">Mail</option> </select> |
That’s all about CSS selector for a checked radio button label using JavaScript and Query.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)