3

i have:

<span id="asdfasdf_test">
<span id="adfaf_test33">
<span id="2342_test">
<span id="34223sdf_testrr">
<span id="asdfsdsdf_test">
<span id="asdf2343sdf_test">

.red {
color: red
}

if span id ends at _test i would like add for this span class .red . how can i make this with jQuery?

LIVE EXAMPLE: http://jsfiddle.net/X6TTd/

Paul Attuck
  • 2,229
  • 4
  • 23
  • 26
  • 2
    Documentation to the rescue: http://api.jquery.com/attribute-ends-with-selector/ Btw. your life example does not contain any JavaScript code and includes Mootools instead of jQuery... that's not particular helpful. – Felix Kling Oct 17 '11 at 14:46
  • possible duplicate of [jQuery Selector: Id Ends With?](http://stackoverflow.com/questions/609382/jquery-selector-id-ends-with) ... please use the search (here and your favorite search engine) before you ask a question. – Felix Kling Oct 17 '11 at 14:48
  • So obviously these guys havent googled this.. It's impossible to miss the jquery documentation.. – Rob Oct 17 '11 at 14:48

2 Answers2

8
$('span[id$="_test"]').addClass('red');

The $= attribute selector means 'ends with'. I added "span" to the jQuery selector since they are all spans in your example, but you can also select the attribute on any element:

$('[id$="_test"]')
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
3

CSS can do that for you! Why do you want to use jQuery? (besides: jQuery understands this CSS Selector)

Here you have it: http://www.w3.org/TR/selectors/#selectors

NE555
  • 76
  • 10
  • Yes, CSS has the same `$=` attribute selector (jQuery uses CSS-style selectors), but it's not supported in all browsers in plain CSS. With jQuery, it is. – Chris Pratt Oct 17 '11 at 15:10
  • Yeah but I think sometimes it's better to use only CSS or at least a CSS fallback. – NE555 Oct 17 '11 at 18:15
  • 1
    Well, of course, it all depends on the situation, but for CSS properties that aren't universally supported, generally JS is the better approach. JS is supported and enabled in the largest majority of browsers. And, now with sites that have universal draw like Facebook, it's very rare to even find a user who has disabled JS, manually. Meanwhile there's not much you can do to make an old browser understand attribute selectors in CSS, and even if you could, JS would be required to do it. Ironically, you'll likely end up with greater user coverage with JS than CSS in this scenario. – Chris Pratt Oct 17 '11 at 19:01