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?
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).
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.
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.
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").
Try this:
$("p:contains('" + vtxt + "')").addClass("on");
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With