2

I have some nodes which may occasionally contain a dot in their ID attribute,

Example: <div id="site_someSite.com"></div>

Then I need to select this element ( I'm using jQuery ) and I do this:

variable = $('#site_'+user); user being 'someSite.com'

And I get nothing in the variable. I suppose this is due to the dot in the name which jQuery is accepting as a class. Anyone has any idea how I can work around this without not-using a dot?

php_nub_qq
  • 13,981
  • 19
  • 68
  • 133
  • possible duplicate of [How to select html nodes by ID with jquery when the id contains a dot?](http://stackoverflow.com/questions/605630/how-to-select-html-nodes-by-id-with-jquery-when-the-id-contains-a-dot) – Teepeemm May 07 '15 at 00:45

4 Answers4

6

You can use it but escape it by backslashes,like $('#example\\.afterdottext');

As per docs

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

Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
6

Working jsFiddle Demo

Use attribute selectors1:

var site = 'someSite.com';
var variable = $('[id="site_' + site + '"]');

// do something
variable.css('background', 'yellow');

References:

5

You can do this -

variable = $('#site_'+user.replace(/\./g,'\\.'));

Demo ---> http://jsfiddle.net/wdJka/2/

Mohammad Adil
  • 44,013
  • 17
  • 87
  • 109
4

If all you need to do is select by the id, then you can use document.getElementById:

var div = document.getElementById('site_'+user);

Note that this will obviously give a native DOM element. If you need a jQuery selection, you can wrap this in the jQuery constructor:

var div = $(document.getElementById('site_'+user));

This has the additional advantage of being faster! Obviously it won't work if you have anything else in your selector.

lonesomeday
  • 224,675
  • 49
  • 309
  • 312