How to select html nodes by ID with jquery when the id contains a dot?
Asked Answered
S

8

194

If my html looked like this:

<td class="controlCell">
    <input class="inputText" id="SearchBag.CompanyName" name="SearchBag.CompanyName" type="text" value="" />
</td>

How could I select #SearchBag.CompanyName with JQuery? I can't get it to work and I fear it's the dot that's breaking it all. The annoying thing is that renaming all my id's would be a lot of work, not to mention the loss in readability.

Note:
Please let's not start talking about how tables are not made for lay-outing. I'm very aware of the value and shortcomings of CSS and try hard to use it as much as possible.

Stallard answered 3/3, 2009 at 9:3 Comment(4)
Is a period in an ID even valid HTML?Flashy
Yes. IDs may contain ‘-’, ‘_’, ‘.’ and ‘:’. w3.org/TR/html4/types.html#type-nameClactonian
Jeps, my pages all validate except for the double <title> tag the asp.net mvc framework generates..Stallard
possible duplicate of How do I get jQuery to select elements with a . (period) in their ID?Lagos
C
234

@Tomalak in comments:

since ID selectors must be preceded by a hash #, there should be no ambiguity here

“#id.class” is a valid selector that requires both an id and a separate class to match; it's valid and not always totally redundant.

The correct way to select a literal ‘.’ in CSS is to escape it: “#id\.moreid”. This used to cause trouble in some older browsers (in particular IE5.x), but all modern desktop browsers support it.

The same method does seem to work in jQuery 1.3.2, though I haven't tested it thoroughly; quickExpr doesn't pick it up, but the more involved selector parser seems to get it right:

$('#SearchBag\\.CompanyName');
Clactonian answered 3/3, 2009 at 10:9 Comment(7)
"#id.class is a valid selector that requires both an id and a separate class to match": As per the HTML spec, IDs must be unique throughout the document. What would "#id.class" be good for? I mean, you can't be any more specific than "#id", can you?Melanite
@Tom: “#id.class” might be good for multiple documents using the same stylesheet, or setting states with client-side-scripting. For example “#navhome.navselected”.Clactonian
@bobince: Yeah, cletus came up with the same example, and I quess it's valid. Still it feels strange to me, and I can't see the genuine advantage of being able to do that. Especially in the light of HTML allowing dots in the ID and the fact that you can always use ".navselected" to achieve the same.Melanite
You might, for example, want a selected #navhome to light up in a different colour to a selected #navabout, but other .navselected properties to be shared. I wouldn't say this situation comes up all the time, but I've certainly needed it occasionally.Clactonian
It's an edge case, but I can follow the logic (you've got my +1 already). The drawback that remains is that since this isn't caught by quickExpr, the getElementById() shortcut in jQuery is probably not used, and thus it will perform worse even though it is an ID. Same goes for my solution.Melanite
Yeah, I would go for ‘_’ rather than ‘.’ if possible; in addition to jQuery performance, the CSS backslash escape is just ugly!Clactonian
I think answer of @Melanite is more elegant, like: $('[id="profile.birthdate"]')Josuejosy
M
137

One variant would be this:

$("input[id='SearchBag.CompanyName']")
Melanite answered 3/3, 2009 at 9:8 Comment(9)
Indeed. Could you tell me why your solution works and $("#SearchBag.CompanyName") doesn't?Stallard
Because .CompanyName is treated as a class selector.Flashy
Quickly looking at the source code, it is either a deliberate design decision or a bug. The regex used to identify id selectors (named quickExpr) does not include the dot as a valid character. The HTML spec however allows it.Melanite
Then howcome your selector does include the dot and mine doesn't?Stallard
@cletus: But since ID selectors must be preceded by a hash #, there should be no ambiguity here. HTML allows a dot in the ID attribute, so should CSS/jQuery. Can you point out a situation where allowing this could cause trouble? (I can't, but I'm not sure.)Melanite
Having a class selector on an ID is possibly useful. Imagine you have a #menu element on every page but want to make it different on one of your pages. #menu.hideme for example? Marginal I know but it's valid.Flashy
This clearly is the superior answer. Works also with variables like this: $("tr[id='" + private_var + "']").css("background-color", "#EEEEEE");Misguided
@Melanite Please note, dot notation with backslashes is much quicker: jsperf.com/jquery-selectors-perf-testJosuejosy
@Melanite I was having the same issue as Boris, so I used backslashes where I was directly referencing the id itself. But problem came when I was getting list of ids with and without dot in them from page, there i could not used backslashes. This have helped me in achieving what I needed. thanksCaesium
A
37

You don't need to escape anything if you use document.getElementById:

$(document.getElementById('strange.id[]'))

getElementById assumes the input is just an id attribute, so the dot won't be interpreted as a class selector.

Athalla answered 6/6, 2013 at 5:33 Comment(1)
Neat solution, also works nicely with dynamic ID that may contain dotsCaro
L
20

Short Answer: If you have an element with id="foo.bar", you can use the selector $("#foo\\.bar")

Longer Answer: This is part of the jquery documentation - section selectors which you can find here: http://api.jquery.com/category/selectors/

Your question is answered right at the beginning of the documentation:

If you wish to use any of the meta-characters ( such as 
!"#$%&'()*+,./:;?@[\]^`{|}~ ) 
as a literal part of a name, you must escape the character with 
two backslashes: \\. For example, if you have an element with id="foo.bar", 
you can use the selector $("#foo\\.bar"). The W3C CSS specification contains 
the complete set of rules regarding valid CSS selectors. Also useful is the 
blog entry by Mathias Bynens on CSS character escape sequences for identifiers.
Laws answered 2/8, 2012 at 12:37 Comment(1)
You do realize that this question is more than three years old and the documentation may not have been the same then, right?Krak
D
12

attr selection seems to be appropriate when your ID is in a variable:

var id_you_want='foo.bar';
$('[id="' + id_you_want + '"]');
Doublet answered 19/9, 2014 at 20:53 Comment(0)
P
4

This is documented in the jQuery selectors API:

To use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

In short, prefix the . with \\.

$('#SearchBag\\.CompanyName')

The problem is that . will match a class, so $('#SearchBag.CompanyName') would match <div id="SearchBag" class="CompanyName">. The escaped with \\. will be treated as a normal . with no special significance, matching the ID you desire.

This applies to all the characters !"#$%&'()*+,./:;<=>?@[\]^`{|}~ which would otherwise have special significance as a selector in jQuery.

Prenomen answered 4/2, 2015 at 11:49 Comment(0)
E
2

Guys who's looking for more generic solution, I found one solution which inserts one backward slashes before any special characters, this resolves issues related to retrieving name & ID from a div which contains special characters.

"Str1.str2%str3".replace(/[^\w\s]/gi, '\\$&')

returns "Str1\\.str2\\%str3"

Hope this is useful !

Endlong answered 4/8, 2013 at 18:2 Comment(0)
A
1

You can use an attribute selector:

$("[id='SearchBag.CompanyName']");

Or you can specify element type:

$("input[id='SearchBag.CompanyName']");
Attested answered 13/3, 2016 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.