views:

7476

answers:

5

Is there a selector that I can query for elements with an ID that ends with a given string?

Say I have a element with an id of "ctl00$ContentBody$txtTitle". How can I get this by passing just "txtTitle"?

+38  A: 

$("element[id$='txtTitle']")

More information available

Mark Hurd
I would look for it ending with '$txtTitle'. It isn't as much of a risk with the 'txt' prefix, but if you selector is 'NameTextBox', it would match 'NameTextBox', 'FirstNameTextBox', LastNameTextBox', etc.
Mark
+13  A: 

Try

$("element[id$='txtTitle']");

edit: 4 seconds late :P

kkyy
+3  A: 
$('element[id$=txtTitle]')

It's not strictly necessary to quote the text fragment you are matching against

Scott Evernden
Thanks for pointing that out.
Josh Stodola
+5  A: 

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

Nick Gilbert
Yes you are right. ID property uses underscore. Name property uses dollar sign.
Josh Stodola
A: 

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")
Anton S. Kraievoy