6

I have an element like this:

<a id="my%20id" href="#">hello</a>

I've been trying desperately to select it with jQuery, but cannot. I've tried:

$('a#my id')                          // obviously won't work
$('a#my\ id')                         // no such luck
$('a#my%20id')                        // unrecognized expression
$('a#my\%20id')                       // still unrecognized
$('a#' + encodeURIComponent('my id')) // same thing as 'a#my%20id'

Is it possible to select this at all with jQuery?

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
2rs2ts
  • 10,662
  • 10
  • 51
  • 95
  • You don't need the a if you are using an ID selector... Will '#my%20id' work? – turtlepick Dec 21 '13 at 04:19
  • possible duplicate of [jquery IDs with spaces](http://stackoverflow.com/questions/596314/jquery-ids-with-spaces) – Kevin Ji Dec 21 '13 at 04:21
  • @mc10 This is not a duplicate, because the id has been encoded. Before it was encoded, $('a#my\ id') worked fine. – 2rs2ts Dec 21 '13 at 04:25
  • 1
    `$(document.getElementById("my%20id"))` will also work. – BrunoLM Dec 21 '13 at 04:26
  • @flaviotsf It's my preference - more self-documenting especially since I am writing a test suite in this case. – 2rs2ts Dec 21 '13 at 04:26
  • 1
    @2rs2ts All of the same solutions work, because the issue is the same: you are using an invalid character in your ID. So your question is still a duplicate. – Kevin Ji Dec 21 '13 at 04:27
  • @mc10 With all due respect, I'm not exactly asking about what a valid id for an element is. I do note this fact, however. – 2rs2ts Dec 21 '13 at 04:33

3 Answers3

10

You can use attribute selector, giving id in quotes will get the exact id.

Live Demo

$('[id="my%20id"]')
Adil
  • 146,340
  • 25
  • 209
  • 204
4

Use the trustworthy document.getElementById:

$(document.getElementById("my%20id")).text();

Performance should be better than using an attribute selector, as you rely on a native method call to find the id. It's a bit more verbose than the other solutions, if that's an issue.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
  • 1
    I would accept this answer if two things were true: (1) I wasn't working inside of an iframe (d'oh! but that's too XY) and (2) I didn't ask for this specifically in jQuery. But yes, that's a great way to do it normally. – 2rs2ts Dec 21 '13 at 04:27
3

Actually you need a lot of escaping here:

$("#my\\%20id").text("HI");

\% is not a valid escape, you want \\% which will escape correctly and get the correct id.

You can check an example on jsFiddle.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • This didn't work, but it may have something to do with my environment and not with the general correctness of your answer. So, upvoted nonetheless. – 2rs2ts Dec 21 '13 at 04:34