0

using jQuery, I'm trying to see if a random id ends with a certain string using the following pseudo code:

var node = $('#foobar');

if (node.attr('id').endsWith('bar')) {
 // do stuff
}

I know for node selection you can go $(id?='bar') , but I need something that works for $.attr().

Any ideas?

tester
  • 22,441
  • 25
  • 88
  • 128
  • possible duplicate of [jQuery Selector: Id Ends With?](http://stackoverflow.com/questions/609382/jquery-selector-id-ends-with) – Donut Aug 19 '11 at 20:53
  • different problem. the suggested duplicate is trying to select an element. i'm trying to take some jQuery object and test to see if the attr('id') ends with something. – tester Aug 19 '11 at 21:01

3 Answers3

1

If you already have the desired object and therefore also have the id string as in your example, then this is just a question about matching something at the end of a string so you could just match the id string vs. a regular expression:

if (node.attr('id').search(/bar$/) != -1) {

}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Try this

if (node.filter("[id$='bar']").length > 0){
   //do stuff
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0
<div id="foo-bar">asd</div>

if ($("div[id$='bar']")) {
 // do stuff
}

http://jsfiddle.net/PsaHQ/1/

Rafay
  • 30,950
  • 5
  • 68
  • 101