Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery contains() with a variable syntax

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?

like image 978
Mircea Avatar asked Feb 03 '10 11:02

Mircea


People also ask

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

What does the $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

How do you check if a variable contains a string in jQuery?

You can check using Javascript . IndexOf() if a string contains substring or not, it returns Index of substring if it is in a string otherwise it returns 0. console.

What is $() in JavaScript?

The $() function The dollar function, $(), can be used as shorthand for the getElementById function. To refer to an element in the Document Object Model (DOM) of an HTML page, the usual function identifying an element is: document. getElementById("id_of_element").


2 Answers

Try this:

$("p:contains('" + vtxt + "')").addClass("on"); 
like image 61
Andrew Hare Avatar answered Sep 22 '22 17:09

Andrew Hare


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"); 
like image 23
Nelo Mitranim Avatar answered Sep 22 '22 17:09

Nelo Mitranim