104

I want to get an element by its href attribute in jquery or javascript. Is that possible?

Mark
  • 2,961
  • 1
  • 16
  • 24
eos87
  • 8,961
  • 12
  • 49
  • 77

4 Answers4

217

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="https://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="https://google.com"]');
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
21

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

jonathancardoso
  • 11,737
  • 7
  • 53
  • 72
5
var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

Adam
  • 43,763
  • 16
  • 104
  • 144
4

Yes.

$('a[href=\'http://google.com\']')

http://api.jquery.com/attribute-equals-selector/

Mark
  • 32,293
  • 33
  • 107
  • 137