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
Add a ment  | 

4 Answers 4

Reset to default 8

You 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