简体   繁体   中英

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"]') ?

$('.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.

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.

<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");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM