Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select element with percent sign (%) in its id with jQuery

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?

like image 588
2rs2ts Avatar asked Dec 21 '13 04:12

2rs2ts


3 Answers

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

Live Demo

$('[id="my%20id"]')
like image 102
Adil Avatar answered Nov 01 '22 06:11

Adil


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.

like image 26
BrunoLM Avatar answered Nov 01 '22 06:11

BrunoLM


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.

like image 41
kevinji Avatar answered Nov 01 '22 08:11

kevinji