1

when using the special character to find the element like as below $("#search@") the exception will occur. how to resolve it? I've tried using the all special character but it's working with * character like $("#search*") without any error, but others #$%^&() throw an error.So why it accepts the * character but why the other character doesn't.

Balaji M
  • 127
  • 1
  • 1
  • 12
  • Check the standard way of ID, class, name attributes nomenclature. – rrk Aug 19 '15 at 17:24
  • 1
    possible duplicate of [Which characters are valid in CSS class names/selectors?](http://stackoverflow.com/questions/448981/which-characters-are-valid-in-css-class-names-selectors) – Jeremy W Aug 19 '15 at 17:28

3 Answers3

2

If you have special character for ids, you should escape them using \\ (two backslashes) when you access them. But as far as I know this will only be allowed with html5.

As stated in jquery selector documentation

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \. For example, an element with id="foo.bar", can use the selector $("#foo\.bar").

alert($("#search\\$").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="search$">Heh</div>
Aruna Tebel
  • 1,436
  • 1
  • 12
  • 24
0

Try utilizing Attribute Equals Selector [name="value"]

$("[id='search@']").click(function() {
  $(this).html(this.id)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="search@">click</div>
guest271314
  • 1
  • 15
  • 104
  • 177
0

Many special characters are not allowed (Which characters are valid in CSS class names/selectors?).

A way to still select what you want, by looking for all but the special character(s) be seeing what some at the start, end, or contained somewhere within the tag's id.

  1. Starts with: jQuery ID starts with

    $('[id^="start-with"]')
    
  2. Ends with: jQuery Selector: Id Ends With?

    $('[id$="ending-part"]')
    
  3. Contained somewhere within: jQuery ID Contains

    $('[id*="any-spot-at-all"]')
    

There are others ways to "skin the cat" of course - some other selector options for example, to find only a part of a id or class or any other HTML tag attribute can be found at http://api.jquery.com/category/selectors/attribute-selectors/ .

Community
  • 1
  • 1
Eric D. Johnson
  • 10,219
  • 9
  • 39
  • 46