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
  • 15,199
  • 21
  • 74
  • 144
  • 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

7

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
  • 120,458
  • 37
  • 198
  • 307
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/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
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
  • 233,373
  • 50
  • 316
  • 318