TDG TDG - 6 months ago 91
jQuery Question

Syntax error, unrecognized expression for href

When i add below script and run. getting,


Uncaught Error: Syntax error, unrecognized expression: ul li
a[href=#!id1]


Not sure which double quote causing the issue. can any one pls help to solve the issue?

HTML

<ul>
<li class="slist selected" id="id1"><a href="#!id10">Test1/a></li>
<li class="slist" id="id2"><a href="#!id20">Test2</a></li>
<li class="slist" id="id3"><a href="#!id30">Test3/a></li>
</ul>


JS

$(document).ready(function () {
var id = "#!" + window.location.href.split("!")[1];
if ($("ul li a[href=" + id + "]").length) {
console.log("present");
} else {
console.log("absent")
}
});

Answer

You need to enclose special characters in quotes when using a attribute based selector.

if ($('ul li a[href="' + id + '"]').length) {

Your version of selector would result

if ($("ul li a[href=#!...]").length) {

The #! will throw unrecognized expression.


My version where the "" escape the characters

if ($('ul li a[href="#!..."]').length) {
Comments