Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Selectors: How to select item with specific class *and* id

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.

like image 855
BAHDev Avatar asked Jan 07 '10 16:01

BAHDev


People also ask

How could you use a selector to choose a specific element with a specific class?

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.

How do you select element by id in jQuery?

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.

How do you select an item with ID student in JS?

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.

What is the difference between id and class selector in jQuery?

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.


1 Answers

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?

like image 144
Peter Štibraný Avatar answered Nov 15 '22 23:11

Peter Štibraný