704

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">

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
Aximili
  • 28,626
  • 56
  • 157
  • 216

5 Answers5

1633
   $('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-...")
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 22
    something changed recently. $('[href$=-abc]') used to work. Now it requires quotes $('[href$="-abc"]') I don't know when it changed. Maybe it was always supposed to require quotes and just happened to work before. – gman Jul 25 '11 at 07:34
  • 13
    Note that "ABC" is case-sensitive! (Just spent quite some time to figure that one out...) – Louis Somers May 24 '12 at 11:09
  • How to get href does not contains ABC in jquery – sf.dev Apr 30 '14 at 22:07
  • 3
    @sf.dev `$('a').filter(function() { return !this.href || !this.href.match(/ABC/); });` – tvanfosson May 01 '14 at 01:37
  • 9
    This works with vanilla javascirpt now. You can simply use `document.querySelectorAll('a[href$="ABC"]')` to achieve this. – k-nut Mar 01 '15 at 19:28
  • `!=` is not a valid attribute selector – bitten Oct 26 '16 at 08:41
  • @bitten the question is about jQuery attribute selectors. It is a valid conditional operation in jQuery. – tvanfosson Oct 26 '16 at 13:41
  • if someone is trying to use a `var` `var name = "ABC"; $('a[href$='+name+']')` – Arun Jan 31 '19 at 17:14
24
$('a[href$="ABC"]:first').attr('title');

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

James Hill
  • 60,353
  • 20
  • 145
  • 161
Ash
  • 241
  • 2
  • 2
16
$("a[href*='id=ABC']").addClass('active_jquery_menu');
Brandon
  • 68,708
  • 30
  • 194
  • 223
Sumit
  • 161
  • 1
  • 2
6
$("a[href*=ABC]").addClass('selected');
Anujith
  • 9,370
  • 6
  • 33
  • 48
Ganesh Anugu
  • 61
  • 1
  • 2
5

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320