jQuery method .find() with special character (&)

Tags: ,

I’m getting a “Syntax error, unrecognized expression” when running the following jQuery:

$element = $('.header__navigation .menu-item > .megamenu__item__link:focus');
var href = $element.attr('href');   // Example: #one-&-two

$('#mega-menu').find(href).toggleClass('active'); // it breaks here

What options do I have where the href value would be #one-&-two and I’m trying to toggle the class on an element within a div#mega-menu with id="#one-&-two" ?

I’ve tried escaping the ‘&’ character in the “href” variable like below:


Maybe an alternative to find() that can take an input like #one-&-two ?


This worked for me:

$('#mega-menu').find("[id='"+ href.substring(1) +"']").toggleClass('active');

See for example following snippet:

  var href = $('a.link').attr('href');   

  $('div.some-class').find("[id='"+ href.substring(1) +"']").text('sss');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="some-class">
     <a class="link" href="#one-&-two"></a>
     <span id="one-&-two"></span>

Source: stackoverflow