I'm trying to select an HTML element on my page that has a specific class and ID. Here's the tag:
<div class="statusLight" id="green"></div>
I tried this with no luck:
$statusLight = $('.statusLight#green');
I know that I could simply say
$statusLight = $('#green');
But I was trying to find a way to select it based on its class as well. Any help would be appreciated.
class selector selects elements with a specific class attribute. To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
Approach: Use jQuery [attribute^=value] Selector to select the element with ID starts with certain characters. Example 1: This example selects that element whose ID starts with 'GFG' and change their background color.
Differentiate the concepts of ID selector and class selector: The only difference between them is that “id” is unique in a page and it is applied to one HTML element while “class” selector can apply to multiple HTML elements.
Both #green.statusLight
and .statusLight#green
are valid selectors and should select element you're looking for. First one will be faster though.
Are you using $(...)
after your document is loaded, i.e. from $(document).ready(function() { ... })
or by placing your script after your element?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With