HTML5 id's special characters and CSS/jQuery selectors
If you set some special characters into an id attribute's value, then you must consider escaping those characters while using CSS jQuery selectors.
by bizamajig
HTML
<!--
Copyright (c) 2010 Sebastien P.
http://twitter.com/_sebastienp
MIT licensed.
---
If you set some special characters into
an id attribute's value, then you must
consider escaping those characters
while using CSS jQuery selectors.
-->
<section id="makes/use/of/slashes">
<h2>Escape special characters ...</h2>
<p>
When you try to retrieve an element by its id with jQuery, you usually do something like this : <code>$("#id");</code>.
</p>
<p>
As we can see in the HTML5 W3C working draft (<a href="http://dev.w3.org/html5/spec/Overview.html#the-id-attribute">take a look at it</a>), the value of a id attribute can now be <strong>a combination of non-spaces characters</strong> so what if, for some reason, we wanted to retrieve this paragraph's parent section by its id ?
</p>
<p>
<code>$("#makes/use/of/slashes");</code> <em class="fail">will fail</em> but there is nothing that actually can't be done here, we just have to <strong>escape the slashes</strong> !
</p>
<p>
<code>$("#makes\/use\/of\/slashes");</code> <em class="fail">will fail too</em> because because of the way jQuery actually handles selectors (<a href="http://api.jquery.com/category/selectors/">see the note</a> at the top of the page). So, all we have to do is to <strong>escape the slashes twice</strong> !
</p>
<p>
<code>$("#makes\\/use\\/of\\/slashes");</code> <em class="pass">will pass</em>, finally ! Also notice that <strong>CSS rules needs</strong> (one time) <strong>escaped special characters</strong> too.
</p>
</section>
CSS
#makes\/use\/of\/slashes {
color: #333;
font: 100% helvetica;
padding: 25px
}
#makes\/use\/of\/slashes > h2 {
font-size: 1.5em
}
#makes\/use\/of\/slashes > p {
margin-top: 1.5em;
text-align: justify
}
#makes\/use\/of\/slashes code {
border: 0.1em dashed #ccc;
color: #960;
display: inline-block;
padding: 0.5em
}
#makes\/use\/of\/slashes strong {
font-weight: bold
}
#makes\/use\/of\/slashes .fail {
color: #900
}
#makes\/use\/of\/slashes .pass {
color: #090
}
#makes\/use\/of\/slashes a {
color: #009
}
#makes\/use\/of\/slashes a:hover {
text-decoration: none
}
JavaScript
var regular = $("#makes/use/of/slashes").length,
escaped_once = $("#makes\/use\/of\/slashes").length,
escaped_twice = $("#makes\\/use\\/of\\/slashes").length;
window.alert("Regular : " + regular + "\nEscaped once : " + escaped_once + "\nEscaped twice : " + escaped_twice);