William
William

Reputation: 1069

Error: Syntax error, unrecognized expression

I was trying to trigger my onclick event until I got the following in console log:

Error: Syntax error, unrecognized expression: li[data-path='00's']

My code is as follows:

$( "li[data-path='00\'s']" ).on("click", function() 
{
    console.log("in 00s");
    $('#replacewithimg').replaceWith('<img id="replacewithimg" src="../assets/img/playlist-icons/00s.png" style="padding-left: 5px;padding-right: 10px;padding-bottom: 5px;">');
    $('#replacewithtext').replaceWith('<b id="replacewithtext" style="font-size:30px;">00\'s Playlist</b>');
    $('#replacewithtext2').replaceWith('<p id="replacewithtext2" style="font-size:18px; padding-top:10px;">Includes Amy Whinehouse, Westlife, The Killers...</p>');
});

If you click on an element matching the li tag which contains a data-path with

00's

Then do its thing. I think is issue is with the escaping single quote?

Upvotes: 0

Views: 2859

Answers (2)

fdomn-m
fdomn-m

Reputation: 28611

Here's some variations, probably best bet is to use a variable if you don't like using \:

// with outer ', inner ", single \
console.log($('div[data-path="00\'s"]').length)
// with outer ", inner ', double \\
console.log($("div[data-path='00\\'s']").length)

// No \, using a variable, with outer ' and inner "
// This doesn't work inline as the js parser sees the '
// rather than it being a jquery limitation
var path = "00's"
console.log($('div[data-path="' + path + '"]').length)

// without inner " or '

// With outer " use double \\
console.log($("div[data-path=00\\'s]").length)
// With outer ' use triple \\\
console.log($('div[data-path=00\\\'s]').length)

// doesn't work
// console.log($("div[data-path=00's]").length)
// console.log($("div[data-path=00\'s]").length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-path="00's">
</div>

Upvotes: 0

bugwheels94
bugwheels94

Reputation: 31910

Use

 $( "li[data-path='00\\'s']" )

instead of

$( "li[data-path='00\'s']" )

First backslash will escape the second backslash in function call send it to function and now the remaining backslash will be used by CSS for CSS selector

PS : Use this instead to avoid escaping the '

$('#replacewithtext').replaceWith("<b id='replacewithtext' style='font-size:30px;'>00\'s Playlist</b>");

DEMO

$( "li[data-path='00\\'s']" ).on("click", function() 
{
    console.log("in 00s");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li data-path="00's"
    >Click</li>

Upvotes: 3

Related Questions