2

I am trying to get an element from my page using jquery :

The element :

<a href="path" id="form1:ctlName">

I am trying to get the element like this and fail :

$('#form1:ctlName')

While this way works :

document.getElementById('form1:ctlName');

The problem is that I need the .css property which is jquery only.

Anyone has any idea how to get the control using jquery?

user779444
  • 1,365
  • 4
  • 21
  • 38
  • From the [**documentation**](http://api.jquery.com/category/selectors/): *"To use any of the meta-characters ( such as ``!"#$%&'()*+,./:;<=>?@[\]^`{|}~`` ) as a literal part of a name, it must be escaped with with two backslashes: ``\\``.*" `:` is a meta-character. – Felix Kling Jun 02 '13 at 12:00
  • possible duplicate of [Handling colon in element id jquery](http://stackoverflow.com/questions/5552462/handling-colon-in-element-id-jquery) – Felix Kling Jun 02 '13 at 12:02

5 Answers5

2

The problem comes with the : in your selector, since jQuery tries to interpret it as a extension for the selectors. Some uses of the colon for selector are the pseudo classes :first or :last, you can get a full list of those selector extensions can be found here.

Try these selectors:

$("[id='form1:ctlName']"); //Method one, encapsulating the id
$("#form1\\:ctlName");     //Method two, escaping the colon

Here's a working demo

Note that according to this answer, calling the native javascript method getElementById(yourId) would be about 10x faster than the other methods, so if performance is paramount you may want to consider using that.

Community
  • 1
  • 1
Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
2

that's because the ':' has a special meaning in jQuery. You should escape it.

$('#form1\:ctlName'); // Does not work

Apparently you should escape it with two slashes:

$('#form1\\:ctlName'); // Works
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
2

More performant than the other answers (looping through all elements to check the ID attribute), is this way:

$(document.getElementById('form1:ctlName'))

jQuery is just a function that wraps DOM elements. You can pass DOM elements to it with no issue.

Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
1

Escape the : with two "\"

$('#form1\\:ctlName')

-With one "\", it does not work. http://jsfiddle.net/m8Vrt/
-With two "\", it works http://jsfiddle.net/eQT6w/1/

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
0

try this out

<a href="path" id="form1_ctlName">
$('#form1_ctlName')

just replace the : with _

: is restricted char in jquery selectors check this url

http://api.jquery.com/animated-selector/

Prog Mania
  • 615
  • 9
  • 14