31

When I add below script and run. I am getting this:

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

I am not sure which double quote causing 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")
    }
});
halfer
  • 19,471
  • 17
  • 87
  • 173
TDG
  • 1,274
  • 1
  • 16
  • 41
  • 1
    According to the W3 specs, the exclamation character is not valid for the id attribute. http://www.w3.org/TR/html4/types.html#type-id – InbetweenWeekends Jul 03 '15 at 02:22

4 Answers4

42

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) {
Shaunak D
  • 20,236
  • 10
  • 45
  • 76
  • 1
    In my scenario, I was using $(document).on("click", "a[href^=#]", function(e) { and I added only single quote a[href^='#']" and it's working. Thanks Shaunak. upvote form my side. – questionbank Aug 26 '19 at 14:15
19

I tried the solution provided by

https://github.com/jquery/jquery/issues/2885

which worked for me. I search for [href=#] in js and replace with [href*=\\#]

a[href*=\\#]:not([href=\\#])
Bikram Shrestha
  • 1,862
  • 23
  • 22
  • I searched for [href=# and wrapped everything between the equals and closing bracket in quotes. "[href=#abc]" became "[href='#abc']" – Damion Gomez Jun 25 '20 at 19:52
4

you may add the below code in functions.php

function modify_jquery() {
if (!is_admin()) {
 wp_deregister_script('jquery');
 wp_register_script('jquery', 'https://code.jquery.com/jquery-1.11.3.min.js');
 wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
  • This worked. It appears jquery below the above version had issues. Thanks for pointing out. – KhoPhi Jun 03 '17 at 22:38
0

I got this error, because I have added these line codes somewhere in my codes;

$("a[href^='#']").click(function(e {
    e.preventDefault();
    var position = $($(this).attr("href")).offset().top; // if you remove this line, then error won't come
});
Abduls
  • 11
  • 2