jQuery Selectors: Select element with specific class and 'title' attribute

MegaMatt picture MegaMatt · Jan 27, 2010 · Viewed 48.3k times · Source

This should be an easy one, but I can't find a good example anywhere. I'm trying to select a particular element on my page that has a class of 'statuslight' and a title attribute of one of three options. The option (it will depend) is stored in a variable called 'currentStatus'. I've seen some examples, and I'm guessing this is the right track, but I need to know for sure:

$(".statuslight[title]='" + currentStatus + "'");

Answer

Joel picture Joel · Jan 27, 2010

Very close:

$(".statuslight[title='" + currentStatus + "']");

Supposing your currentStatus is an array, you could get all statuslight elements with a title that contains any of the currentStatus values with:

$(".statuslight[title='" + currentStatus[0] + "'], .statuslight[title='" + currentStatus[1] + "'], .statuslight[title='" + currentStatus[2] + "']");

Alternatively, if your title has multiple statuses (title="status1 status2 status3"), and currentStatus is only one item you would use this selector:

$(".statuslight[title~='" + currentStatus + "']");