SausageFingers
SausageFingers

Reputation: 1846

jQuery selector problem when using a single parenthesis

If I include a single parenthesis in a :contains selector I get an error.

e.g.

$("a:contains('Speed (mph')")

returns the error

Syntax error, unrecognized expression: (mph')

if I add the closing parenthesis at the end, the statement runs fine. however, I need to be able to query where there is often a single parenthesis.

What's going on here and how do I sidestep this?

EDIT

In my actual code the :contains part is passed in as a variable

e.g

var searchText = 'Speed (mph';
var result = $("a:contains('" + searchText  + "')");

Upvotes: 2

Views: 3317

Answers (2)

dtbarne
dtbarne

Reputation: 8200

You should be able to use $("a:contains('Speed \\(mph')")

From http://api.jquery.com/category/selectors/

If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors.

Upvotes: 3

T Nguyen
T Nguyen

Reputation: 3415

As from Matthew Flaschen's link, you could use the filter function like this:

    var searchRegex = new RegExp("Speed \\(mph","g");
    var result = $('a').filter(function(i, el) {
        return $(el).text().match(searchRegex);
    });

Upvotes: 0

Related Questions