Reputation: 54756
I've tried to search for a user-agent string in a table using jQuery. If I search like this it is not found:
jQuery("table.make-html-table
td:contains('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
.css("background","yellow");
If I search like this - slashes before \( - then it give me an error:
jQuery("table.make-html-table
td:contains('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
.css("background","yellow");
Error:
"Syntax error, unrecognized expression: (comp...
How can I properly escape that string so that I can search for cells that contain it with jQuery?
Upvotes: 2
Views: 1472
Reputation: 95030
Use two slashes:
jQuery("table.make-html-table
td:contains('Mozilla/4.0 \\(compatible; MSIE 6.0; Windows NT 5.1\\)')")
.css("background","yellow");
Alternate solution:
jQuery("table.make-html-table td:contains('Mozilla/4.0'):contains('compatible; MSIE 6.0; Windows NT 5.1')").css('background-color','yellow');
Another solution using textEquals custom selector
jQuery.expr[':'].textEquals = function(a, i, m) {
return jQuery(a).text() === m[3];
};
...
jQuery("table.make-html-table td:textEquals('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')")
.css("background","yellow");
Upvotes: 2
Reputation: 214949
The relevant part in sizzle is
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
which makes me think there is no way. Looks like it only accepts arguments that contain no parenthesis at all, or only one level thereof like :contains("(foo)")
. An obvious improvement would be accept anything if an argument is quoted, hope this will be fixed soon.
For the time being, a workaround would be to write a selector that would accept escaped arguments, for example:
$.extend($.expr[':'], {
containsEscaped: function (el, index, m) {
var s = unescape(m[3]);
return $(el).text().indexOf(s) >= 0;
}
});
usage:
var p = $("p:containsEscaped('foo%28bar')");
In action: http://jsfiddle.net/9wWP5/
Upvotes: 4