jQuery find anchor tag with exact href

jetlej picture jetlej · Nov 7, 2011 · Viewed 35.5k times · Source

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+'"]');

Answer

meagar picture meagar · Nov 7, 2011

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+'"]');