Select <a> which href ends with some string

JqueryStringAnchorHref

Jquery Problem Overview


Is it possible using jQuery to select all <a> links which href ends with "ABC"?

For example, if I want to find this link <a href="http://server/page.aspx?id=ABC">

Jquery Solutions


Solution 1 - Jquery

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

Solution 2 - Jquery

$('a[href$="ABC"]:first').attr('title');

This will return the title of the first link that has a URL which ends with "ABC".

Solution 3 - Jquery

$("a[href*='id=ABC']").addClass('active_jquery_menu');

Solution 4 - Jquery

$("a[href*=ABC]").addClass('selected');

Solution 5 - Jquery

Just in case you don't want to import a big library like jQuery to accomplish something this trivial, you can use the built-in method querySelectorAll instead. Almost all selector strings used for jQuery work with DOM methods as well:

const anchors = document.querySelectorAll('a[href$="ABC"]');

Or, if you know that there's only one matching element:

const anchor = document.querySelector('a[href$="ABC"]');

You may generally omit the quotes around the attribute value if the value you're searching for is alphanumeric, eg, here, you could also use

a[href$=ABC]

but quotes are more flexible and generally more reliable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAximiliView Question on Stackoverflow
Solution 1 - JquerytvanfossonView Answer on Stackoverflow
Solution 2 - JqueryAshView Answer on Stackoverflow
Solution 3 - JquerySumitView Answer on Stackoverflow
Solution 4 - JqueryGanesh AnuguView Answer on Stackoverflow
Solution 5 - JqueryCertainPerformanceView Answer on Stackoverflow