Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select an element with a non-alphanumeric id using jQuery?

Tags:

jquery

Axl Rose's wiki page contains an element with the id:

1983.E2.80.931986:_Early_years

I'm using $('#1983.E2.80.931986:_Early_years') to get this element but that fails.

What's the correct selector to use if I want to select this element by id?

like image 765
Dorsey Avatar asked Aug 07 '12 12:08

Dorsey


5 Answers

Straight from from the docs:

If you wish to use any of the meta-characters (such as !"#$%&'()*+,./:;<=>?@[\]^&a{|}~) 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").

Corollary:

jQuery.escapeSelector = function(str) {
  return str.replace(/[!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~]/g, "\\$&");
}

// ...

$('#' + $.escapeSelector('1983.E2.80.931986:_Early_years'))
like image 65
Tomalak Avatar answered Oct 22 '22 04:10

Tomalak


you can use javascript for that

document.getElementById('1983.E2.80.931986:_Early_years')

like image 33
rahul Avatar answered Oct 22 '22 04:10

rahul


Since there are those types of characters, I personally find that the easiest and most readable way is to search by ID itself such as:

$('[id*="1983.E2.80.931986:_Early_years"]')​​​​​​​ // will search for the ID anywhere

Much easier and less confusing way than having to escape characters, etc. Especially since if you ever change the ID name somehow, you won't have to worry about it's naming.

This makes the most sense if you build this ID dynamically from back-end code, it'll always prepulate correctly and work.

http://jsfiddle.net/Yt8D9/

like image 20
Mark Pieszak - Trilon.io Avatar answered Oct 22 '22 04:10

Mark Pieszak - Trilon.io


The : disrupt the selection because it's reserved by css pseudoclasses (e.g. :hover). Try backslashing the :

like image 25
Lord Spectre Avatar answered Oct 22 '22 06:10

Lord Spectre


escape the : and .

$('#1983\\.E2\\.80.931986\\:_Early_years')
like image 21
kgautron Avatar answered Oct 22 '22 04:10

kgautron