Jack Thor
Jack Thor

Reputation: 1604

Multiple dot in element Id a No no?

Edit

Thank you for all the comment and answer.I am baffled, I am able to fix the problem after trying out the different answers, but now is not able to reproduce the problem ??? I don''t know what happened.

What I am trying to do is get an element by id, but this id contains multiple dots in it because the id is the "path" from in an XML doc. So I assume that if you have multiple dot in the id name even though you have escaped them it will not work?

var triggerElementID = "a.b.c.d";
var eleId = triggerElementID.replace(/\./g, "\\\\.");
console.log(eleId);
var thisele = $('#' + eleId);
console.log(thisele);

The above code is what I have it it does escape the the dot, console.log prints out this a\\.b\\.c\\.d while the console.log of thisele prints out this

[prevObject: b.fn.b.init[1], context: document, selector: "#a.b.c.d", jquery: "1.9.1", constructor: function…]
context: document
length: 0
prevObject: b.fn.b.init[1]
selector: ""#a.b.c.d"
__proto__: Object[0]

Upvotes: 2

Views: 541

Answers (3)

Barmar
Barmar

Reputation: 782148

You have too many slashes in your replacement string.

var triggerElementID = "a.b.c.d";
var eleId = triggerElementID.replace(/\./g, "\\.");
var thisele = $("#"+eleId);
console.log(thisele);

FIDDLE

Upvotes: 0

Juan
Juan

Reputation: 5050

when i encountered this problem i was able to use this:

$("[id='" + eleId +"']");

http://jsfiddle.net/tmw63/

Upvotes: 3

Fergus In London
Fergus In London

Reputation: 1203

jQuery uses the sizzle.js CSS3 selector engine. Which will translate them to a.b.c.d to a chained selector, where . takes on it's traditional meaning of a class. So it would be equivelant of:

a with [a class of] b [and a class of] c [and a class of] d

Now sizzle, and therefore jQuery, does mean that escaped selectors are supported (See here) but should be escaped with two backslashes. (\\)

It would appear that there may be an issue with your regex if jQuery is still saying the selector is a.b.c.d despite trying escape them.

-> var triggerElementID = "a.b.c.d";
-> var eleId = triggerElementID;//.replace(/\./g, "\\\\.");
undefined
-> eleId
"a.b.c.d"

Testing it in a developer console supports this theory too.

Edit: Didn't see that the .replace() call was commented out in your above code. Works correctly when uncommented...

Upvotes: 1

Related Questions