30

I have an "uncaught exception: Syntax error, unrecognized expression: )" in a jQuery application.

The code is:

<script>
    $(document).ready(function(){                      
        $('.drag').click(function() {
           $('.drag').each(function(i) {
                $(this).addClass('test' + i)
            });  

           var vtxt = $(this).text();
           $("p").removeClass("on");
           $("p:contains("+ vtxt +")").addClass("on");

       });
    });

The problem is when I add the variable vtxt to a contains: $("p:contains("+ vtxt +")").addClass("on");

I've tried several quotes but it just does not work. What is the right syntax for adding a variable to a contains?

2
  • 1
    What's the value of vtxt. It might contain brackets. Commented Feb 3, 2010 at 11:23
  • This isn't jQuery related per se. It's your JavaScript input to contains() that is syntactically incorrect. :) Commented Feb 3, 2010 at 11:33

3 Answers 3

61

Try this:

$("p:contains('" + vtxt + "')").addClass("on");
Sign up to request clarification or add additional context in comments.

7 Comments

vtxt does not contains brackets. Andrew's response gave me a valid syntax, it works now. Thank you!
make sure you you escape the vtxt contents as it will fail if it ever contains the ' or " character ..
How should I escape the vtxt?
With backslashes. Or just loop over all p elements filtering for p.text().indexOf(vtxt)!==1. This avoids the escaping issue and is no slower than the selector version, since it's a non-standard selector jQuery has to implement in the same sort of way itself.
If this answer is fit your needs you can accept it, isn't it?
|
9

Old question, but I must leave a note for future generations. Andrew's answer (the accepted one) didn't work for me. What did work was using a pre-made string as selector. Borrowing OP's examples:

var selector = "p:contains("+ vtxt +")";
$(selector).addClass("on");

1 Comment

Agee! Accepted answer did also not work for me. This one does! (2021)
3

I have used this answer in order to solve a similar problem.
I want to prevent the use of " and '

When using $("p:contains('" + valor + "')").addClass("on");, it works.

But when using $('p:contains('" + valor + "')**'**).addClass("on"), it does not!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.