Combining a class selector and an attribute selector with jQuery

JavascriptJqueryJquery Selectors

Javascript Problem Overview


Is it possible to combine both a class selector and an attribute selector with jQuery?

For example, given the following HTML:

<TABLE>
  <TR class="myclass" reference="12345"><TD>Row 1</TD></TR>
  <TR class="otherclass" reference="12345"><TD>Row 2</TD></TR>
  <TR class="myclass" reference="12345"><TD>Row 3</TD></TR>
  <TR class="myclass" reference="54321"><TD>Row 4</TD></TR>
</TABLE>

What would be the selector I can use to select rows 1 and 3 only?

I have tried:

$(".myclass [reference=12345]") // returns nothing

$(".myclass, [reference=12345]") // returns all 4 rows (yes, I know the comma means 'or')

I'm sure the answer is very simple and I have tried searching the jQuery forums and documentation but I can't seem to figure this one out. Can anyone help?

Javascript Solutions


Solution 1 - Javascript

Combine them. Literally combine them; attach them together without any punctuation.

$('.myclass[reference="12345"]')

Your first selector looks for elements with the attribute value, contained in elements with the class.
The space is being interpreted as the descendant selector.

Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).

Solution 2 - Javascript

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

Solution 3 - Javascript

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Solution 4 - Javascript

This will also work:

$(".myclass[reference='12345']").css('border', '#000 solid 1px');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason ChildView Question on Stackoverflow
Solution 1 - JavascriptBoltClockView Answer on Stackoverflow
Solution 2 - JavascriptNick PyettView Answer on Stackoverflow
Solution 3 - JavascriptDanielView Answer on Stackoverflow
Solution 4 - JavascriptTherichpostView Answer on Stackoverflow