Search code examples
jqueryanchorhref

jQuery find anchor tag with exact href


I'm using the following code to find anchor tags with a matching href URL. Currently it will return anchors linking to the requested URL, eg. /images AND any links to subfolders of that url, eg. /images/recent. I would like it to only return the first if I'm only asking for /images.

$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');

Solution

  • You're using ^=, the Attribute Starts-With selector. As its name suggests, it matches attributes whose values start with the match string. Instead, use =, the Attribute Equals selector which requires an exact match:

    $menuChildren = $menuChildren.has('a[href="'+url+'"]');