Dealing with JSF ids in CSS and Javascript (JQuery)

Hi everyone,

If you ever had the opportunity to work with JSF applications (or JSF’ish applications like XEO Applications) you may have noticed that most elements in the page have these weird ids like form:input

Imagine the following example in a XEO Application:

<xvw:form id='form'>
   <xvw:attribueText id='name' objectAttribute='username'>
</xvw:form>

The resulting HTML would create a div for the input like the following:

<div id='form:name'>
 ...
</div>

Now, if you want to use Jquery to do something to this element, you would probably do it like this:

$("#form:name")

The problem is that you can’t do this, because in Jquery selectors the colon “:” is a special character and cannot be used like this to select an id. In order for the jquery selector to work you have to escape the colon with a double backslash, like the following:

$("#form\\:name")

But that is one ugly piece of code… you can do the following to ease the pain:

$(document.getElementById('form:name'))

Document.getElementById does not interpret selector, as such there’s no problem having the colon, and since the jQuery selector accepts a DOM element, all is well. If you’re using the XEO Framework, you can do the following as well:

$(XVW.get('form:name'))

And what about CSS? 

Well with CSS the problem is the same, you cannot have the colon in identifiers, so you have to escape it, like the following:

/* Wrong */
#form:name{
 color : red;
}

/* Correct */
#form\:name{
 color : red;
}

There’s just one little problem… this doesn’t work in IE6/7 (shocking, I know). In order to have a compatible solution you need the following:

/* Correct! Compatible with IE 6/7 */
#form\3A name{
  color : red;
}

And I think this pretty much nails it 🙂 Hope it helps someone!
Happy coding!

6 thoughts on “Dealing with JSF ids in CSS and Javascript (JQuery)

Leave a Reply

Your email address will not be published. Required fields are marked *