Get an Element by Href Attribute using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

banner

Photo by Olly Joy

Get an Element by Href Attribute using JavaScript #

Use the querySelector() method to get an element by an href attribute, e.g. document.querySelector('a[href="https://example.com"]'). The method returns the first element that matches the selector or null if no element with the provided selector exists in the DOM.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <a href="https://example.com">Example</a> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// โœ… Get first element by href attribute const el1 = document.querySelector('[href="https://example.com"]'); console.log(el1); // ๐Ÿ‘‰๏ธ a // โœ… Get ALL elements by href attribute const elements1 = document.querySelectorAll('[href="https://example.com"]'); console.log(elements1); // ๐Ÿ‘‰๏ธ [a] // โœ… Get element by Partially Matching Href attribute const el2 = document.querySelector('[href*="example.com"]'); console.log(el2); // ๐Ÿ‘‰๏ธ a // โœ… Get ALL elements by Partially Matching Href attribute const elements2 = document.querySelectorAll('[href*="example.com"]'); console.log(elements2); // ๐Ÿ‘‰๏ธ [a]

The first example uses the document.querySelector method to get the first element that has an href attribute with the value of https://example.com.

index.js
const el1 = document.querySelector('[href="https://example.com"]');

If an element with the provided selector does not exist in the DOM, the querySelector() method returns null.

The second example uses the document.querySelectorAll method with the exact same selector to get a collection of the elements that have the href attribute with the specified value.

index.js
const el2 = document.querySelector('[href*="example.com"]');

In the third example, we get an element by partially matching the value of its href attribute.

index.js
const el2 = document.querySelector('[href*="example.com"]');

This selector checks if the string example.com is contained anywhere in the element's attribute value.

If you need to narrow things down to a specific element, e.g. an a tag, you can start the selector with the tag name.

index.js
const el1 = document.querySelector('a[href="https://example.com"]'); console.log(el1); // ๐Ÿ‘‰๏ธ a

The example above gets the first a element that has an href attribute with the value of https://example.com.

This would not match any other element with the specified href value.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee