Christian Pineault
Christian Pineault

Reputation: 87

quotes in Jquery selectors

I read a couple of answer about a similar question and people always say that there is no difference between a single and a double quote. The problem is I have a little line of code that somehow seem to matter...

$("li[data-type|='veg']").append(' (v)');

this code do what I want him to do: put a (v) at the end of the link but this code:

$("li[data-type|="veg"]").append(' (v)');

does not work. Why? Does it have to do with the browser? I'm new to jquery and it's the first time I see the type of quote making a difference.

Thanks

Upvotes: 0

Views: 3273

Answers (3)

FlavorScape
FlavorScape

Reputation: 14289

This is simply how js is parsed. You have to remember that you're passing a STRING as an argument to the jquery function. In this particular string, there is an expression that jquery parses (a selector), that can contain a quotation mark. If you use the same type of quote, you accidentally terminate the string instead of inserting it in the string. If you notice the color change in the string...

so you have to escape it with a backslash \" that literally tells the parser to ignore it (it's just part of the string) so that your string can stay intact.If you use "mismatched" quotes inside the string, you're kosher.

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

A string that starts with double quote can contain single quotes and vice versa without escaping.

Both of these are valid:

$("li[data-type|='veg']");
$('li[data-type|="veg"]');

however if you use the same quotes within the string that start the string, you need to escape them

$("li[data-type|=\"veg\"]");

This has nothing to do with jQuery. It is just how javascript handles strings

Upvotes: 0

krillgar
krillgar

Reputation: 12805

You need to escape the " by adding a \: \".

Here is a list of many other special characters, and how to escape them.

Upvotes: 1

Related Questions