I have a bunch of HTML with tags like this:
<div id="Field~1">Text text</div>
I can't use normal ID selectors like:
alert($("#Field~1").text())
I'm guessing it's something to do with the "~" but is it possible to reference these type still?
I have setup a JSfiddle here: http://jsfiddle.net/4M97c/
You need to escape all occurence special character in selectors with \\\\
.
First Approach:
alert($("#Field\\~1").text())
Second Approach:
var ID="Field~1";
alert($("[id='"+ID+"']").text())
You need to escape special character ~
with double backslashes \\\\
. From the docs :
To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\\\
alert($("#Field\\~1").text())
Arguably the easiest (and best performing) way to deal with special characters in an identifier is to use getElementById()
and wrap it inside a jQuery object.
alert($(document.getElementById('Field~1')).text());
Besides selectors, the $()
also accepts a DOM element and turns it into a jQuery object.
just do this:
alert($('[id="Field~1"]').text())
This is a string representation of id so you don't have to worry about escaping special characters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.