Showing posts with label escape. Show all posts
Showing posts with label escape. Show all posts

Tuesday, July 28, 2009

Target elements with ids that contain special characters using jQuery

Let's say you have some HTML elements with ids like this one:

<div id="form~myform$div~mydiv[1]#value"></div>

And you would like to target this element using jQuery.
This will not work because of the special characters used in the element's id.
If you execute the following jQuery:

$("div").each(function() {
var divId = this.id;
var jQueryFound = $('#' + this.id).length;

alert("Div id is '" + divId + "' and jQuery found " + jQueryFound);
});

The result is: Div id='form~myform$div~mydiv[1]#value' and jQuery found 0.
JQuery cannot find the element id because it contains meta-characters that jQuery parses as part of the selector.
To solve this problem i wrote a method which escapes the special characters so jQuery parses them as part of the id.

var jEscape = function(jquery) {
jquery = jquery.replace(new RegExp("\\$", "g"), "\\$");
jquery = jquery.replace(new RegExp("\~", "g"), "\\~");
jquery = jquery.replace(new RegExp("\\[", "g"), "\\[");
jquery = jquery.replace(new RegExp("\\]", "g"), "\\]");
jquery = jquery.replace(new RegExp("#", "g"), "\\#");
return jquery;
};

Now execute the following code to see that it works:

$("div").each(function() {
var divId = this.id;
var escapedId = jEscape(this.id);
var jQueryFound = $('#' + escapedId).length;

alert("Div id is '" + divId + "' which is escaped to '" + escapedId + "' and jQuery found " + jQueryFound);
});

The result is: Div id is 'form~myform$div~mydiv[1]#value' which is escaped to 'form\~myform\$div\~mydiv\[1\]\#value' and jQuery found 1.

If you want to escape all the possible jQuery meta-characters, expand the method to escape these: ;&,.+*':"!^()=>|/

/Ruud