views:

344

answers:

3

Hi all,

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.

Thanks.

+2  A: 

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?

Peter Štibraný
Thanks Peter for the quick reply. It actually ended up being a typo with "Light" instead of "light". Both methods you gave ended up working.
BAHDev
+5  A: 

I'm not entirely sure why you would want to do this.

An ID should be unique, and therefore when you select it, there is no need for any further specialisation. If not then you need to modify your HTML to make it so.

This scenario would only make sense if you were combining a class selector with an element selector, e.g.

$("div.statuslight")

But in your example, there's just no point, as you have an ID anyway!

James Wiseman
James, I agree with you. Really more of a readability thing in my code, but you're right.. all IDs are unique anyway, so why have to filter them more? My problem ended up being a typo by the way..
BAHDev
There is the case where you want to do event delegation on an element only when it has a class. Say you have a drag'n'drop element and you only want it to be clickable when it has been given a certain class (via some sort of interaction).
Alex Sexton
+2  A: 

Why would you need to select on the class as well? IDs should be unique so adding the class to that wouldn't buy you anything. If you just use ID it's more efficient because then jQuery can just use the native getElementByID which is always the fastest. Keep your queries simple when you can.

Parrots
@Parrots, I do agree. This is more of a readability thing in my code rather than a functional need. Thanks for the advice.
BAHDev
One reason for doing this may be that class of the element changes and he wants to select element only when it has given class. (Ok, just guessing, but the point is that there may be reason for this). [repeating same comment as above]
Peter Štibraný