jQuery selector for uncommon tag ID

195 Views Asked by At

I have this tag ID, pretty uncommon:

<select name="/State" id="/State">

It seems I cannot use jQuery selector $('#/State') to select this object.

I can select it using $("#\U002FState"), but I cannot print the id attribute:

javascript:alert($("#\U002FState").attr('id'))

What can I do to correctly select this object?

3

There are 3 best solutions below

2
On BEST ANSWER

add \\ before / $('#\\/State')

Additional links:

jQuery selectors: http://api.jquery.com/category/selectors/

W3C recommendation: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier

0
On

Unless you're only supporting HTML5 browsers, you'll have issues when selecting by ID, because a / in an ID is not valid in HTML4.

http://www.w3.org/TR/html401/types.html#type-name

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

You could use the attribute-equals-selector[docs], but performance will degrade:

$('select[id="/State"]');

Though it's helpful to include the element-selector[docs] as I did above.

Here's a working example: http://jsfiddle.net/LVEjS/

0
On

as explained here / is not a valid character in id's, so your tags are not standards compliant and it's better to fix that problem than to work around it.