jQuery find anchor tag with exact href
37,560
Solution 1
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+'"]');
Solution 2
If you want to match the href exactly then use the [href=...]
version
$menuChildren = $('a[href="' + relativeUrl + '"]');
Related videos on Youtube
Author by
jetlej
Updated on November 08, 2020Comments
-
jetlej over 3 years
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+'"]');
-
jetlej over 12 yearsAH there's the explanation I needed. Thanks, will accept the answer in 3 minutes