admin管理员组文章数量:1279182
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: /
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/4M97c/
Share Improve this question asked Apr 2, 2014 at 9:31 user3488585user3488585 301 silver badge6 bronze badges 1-
2
The
~
is also called the next siblings selector. – Ja͢ck Commented Apr 2, 2014 at 9:33
4 Answers
Reset to default 8You need to escape all occurence special character in selectors with \\
.
First Approach:
alert($("#Field\\~1").text())
Working Demo
Second Approach:
var ID="Field~1";
alert($("[id='"+ID+"']").text())
Working Fiddle
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())
Updated Fiddle
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.
本文标签: javascriptJquery ID Selectors not workingStack Overflow
版权声明:本文标题:javascript - Jquery ID Selectors not working - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741225176a2361722.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论