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?
You can use attribute selector, giving id in quotes will get the exact id.
Live Demo
$('[id="my%20id"]')
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With