Using a jQuery selector on an ID containing a Pipe (|) Character Programming 24 FEB 2012

I’m quite fond of using the pipe (|) character in tag, id and name properties because it just seems visually such a great delimiter to use when stuffing a string full of useful information to be extracted via splitting or exploding at a later stage.

However, here’s a nasty one which you might not be aware of – jQuery selectors do in fact no enjoy special characters like the pipe ‘|’ – for the very reason that it’s a special character!

So running a selector on an ID which contains a | in the normal fashion will fail (i.e. not find anything):

$('#id|123')

To get around identifiers that use special characters like our friend the |, you need to delimit it so:

$('#id\|123')

And now you know! :)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • I used something like this on my last project:

    /* the HTML */

    /* the JS  */
    var data = $(“#some-data”).val();

    data = data.replace(/’/g, “””);

    data = $.parseJSON(data); 

    alert(data.id);

    What do you think?