How To Get An Element By Href Attribute Using JavaScript

Get an Element by Href Attribute using JavaScript

Hello guys,  today we will learn about how to get an element by Href attribute using JavaScript in two different ways: Using the querySelector() method and getElementById(). Read the following article and then discuss this topic together.

Get an element by Href attribute using JavaScript

Using the querySelector() method

The first way we want to introduce in this article is the querySelector() method. This method will return the matched elements as a CSS selector, and it will throw return an error if the selector is not matched.

Syntax:

document.querySelector(CSS selectors)

Parameter: One or more CSS selectors. If you have multiple selectors, separate each selector with a comma.

Return value: The return value is a NodeList.

Code example:

In this example, we use the querySelector() method with the href attribute. Let’s see the code below to get more information.

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 id="header"></h1>
    <a id="home" href="https://learnshareit.com/">LearnShareIT</a>
    <script src="script.js"></script>
  </body>
</html>
// Using the querySelector() method with href attribute
var element = document.querySelector('[href*="learnshareit.com"]').href;
console.log("The element is: ", element)

Output

The element is
https://learnshareit.com/

Using the getElementById() method

The next way is the getElementById() method. The getElementById() method returns an element with a specified value and will return null if the element does not exist in the tag. We already explained how to use the getElement in this article. You can read it to get more information about this method.

Syntax:

document.getElementById(id)

Parameter:

  • id: the id value of an element.

Return value: the return value is the element with a specified id, and otherways will return null.

Example:

In this example, we call the getElementById() method to get the element and call the href attribute to get the href attribute. Let’s see the code example below.

Index.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <h1 id="header"></h1>
    <a id="home" href="https://learnshareit.com/">LearnShareIT</a>
    <script src="script.js"></script>
  </body>
</html>

Script.js

// Using the getElementById() method with href attribute
var element = document.getElementById("home").href;
console.log("The element is: ", element)

Output

The element is: 
https://learnshareit.com/

Summary

Through this article, we hope you know how to get an element by Href attribute using JavaScript. We have explained two methods in this article, but we think the solutions using the querySelector() method is useful and easy to use.

Have a nice day, and leave your comment here if you have any questions!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *