gsklee
gsklee

Reputation: 4944

jQuery - How to combine multiple elements with same class name in one selector?

Sorry about the cranky title, here's the example:

<table>
  <tr>
    <th class="hey-1-aa"></th>
  </tr>
  <tr>
    <th class="hey-2-aa"></th>
  </tr>
  <tr>
    <td class="hey-1-bb"></tr>
  </tr>
  <tr>
    <td class="hey-2-bb"></tr>
  </tr>
</table>

Is there any better way to selects all the THs/TRs start with the class prefix "hey-2-", with something less verbose than $('th[class^="hey-2"], td[class^="hey-2"]')?

Upvotes: 0

Views: 799

Answers (4)

nnnnnn
nnnnnn

Reputation: 150030

You could try this:

$('tr > [class^="hey-2"]')

That is, select any children of each tr element that have a class starting with "hey-2".

Demo: http://jsfiddle.net/CCuxX/

(Or for markup exactly like that in the question: $('tr:odd > *'))

I know that obviously you've simplified your markup for the question, but as it stands you seem to be using classes as unique identifiers - if so you should use ids.

Upvotes: 0

nathan gonzalez
nathan gonzalez

Reputation: 11987

$('.hey-2')

the selectors for sizzle (the jquery selector engine) begin with basic css and then move from there. so if you can style an element with a selector, you can grab it from jquery the same way.

for a list of selectors take a look at the jquery api

EDIT

so i would think the first thing to eliminate is limiting it to tr/th and just doing something like

$('table [class^=hey-2]')

that simplifies it quite a bit.

i tend to agree with the other answers though. if the items legitimately have something in common, why not give them a common class? instead of class="hey-2-aa" make it class="hey-2 aa" then you really can just use the original answer i posted.

Upvotes: 2

ZeeCoder
ZeeCoder

Reputation: 991

<table>
  <tr>
    <th class="hey-1-aa"></th>
  </tr>
  <tr>
    <th class="hey-2-aa sameclass"></th>
  </tr>
  <tr>
    <td class="hey-1-bb"></tr>
  </tr>
  <tr>
    <td class="hey-2-bb sameclass"></tr>
  </tr>
</table>

$(".sameclass");

Upvotes: 1

Vitor Braga
Vitor Braga

Reputation: 2212

Remember that you can use more than 1 class for an element. So, maybe it would be useful set more classes to the elements. It will be simpler to select.

Upvotes: 1

Related Questions