4

As you may be aware, HTML5 allows more characters to be used in ID names - see the HTML5 spec which now has space as the only invalid character. Attempting to use this with JQuery shows JQuery ignoring all characters in the ID after a particular valid character, '/'.

<section>
    <div id='foo/bar'>
        YAAY
    </div>
    <div id='foo'>
        BOO
    </div>
</section> ​

Logging the 'foo/bar' element

console.log(​$(document).find('div#foo/bar')​​​​)​

Shows the incorrect element being returned:

[
<div id=​"foo">​
    BOO
​</div>​
]

This is using both the current stable JQuery (1.7.1) and the current JQuery edge.

Is this a JQuery bug, or am I doing something wrong?

Rob W
  • 341,306
  • 83
  • 791
  • 678
mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

4

Escape the slash (demo: http://jsfiddle.net/m9NT8/):

console.log(​$(document).find('div#foo\\/bar')​​​​)​

PS. $(document).find('selector') is equivalent to $(selector).

This behaviour is defined in a RegEx at Sizzle's source code, line 374:

ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    That works. Further research shows that JQuery mentions the need to escape characters for selectors on http://api.jquery.com/category/selectors/ "If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes" Annoying, but oh well. – mikemaccana Mar 17 '12 at 14:31
  • Ack re: document.find, in my (non stackoverflow test case) app I'm working off a string in memory, rather than the document. – mikemaccana Mar 17 '12 at 14:34
  • Ah, that was the trick :D Sorry for that, I will delete my previous comment. – Bartosz Grzybowski Mar 17 '12 at 14:43