This article will demonstrate the approaches to get an element by the href attribute using JavaScript.
How to Get an Element by href Attribute in JavaScript?
The element can be fetched by the “href” attribute using the “document.querySelectorAll()” method. This method fetches all the elements matching a CSS selector(s) and returns a node list. More specifically, the stated method can be implemented to access the specified href attribute against the “<a>” anchor element and display the corresponding element.
Syntax
In the given syntax:
“selectors” corresponds to one or more than one CSS selector.
Example 1: Get an Element by href Attribute
In this example, the “<a>” anchor element will be fetched by accessing the “href” attribute via the stated method:
<script type="text/javascript">
let get = document.querySelectorAll('[href="https://google.com"]');
console.log("The element fetched by href attribute is:", get);
</script>
In the above code snippet:
- Firstly, specify the “href” attribute and the stated “URL” respectively, within the anchor “<a>” element.
- In the JS code, access the href attribute by applying the “document.querySelectorAll()” method having the specified URL in the previous step as its parameter.
- Lastly, display the corresponding element, i.e., “<a>” against the specified href attribute.
Output
In the above output, it can be seen that the corresponding “<a>” element is retrieved with the help of the specified href attribute.
Example 2: Get an Element by Matching the href Attribute Partially
In this example, the corresponding element will be fetched by specifying the href attribute partially as well:
<script type="text/javascript">
let get = document.querySelectorAll('[href*="google.com"]');
console.log("The element fetched by the partial href attribute is:", get);
</script>
Perform the following steps in the above code:
- Firstly, likewise, include the “href” attribute and specify the stated “URL” within the “<a>” element.
- In the JavaScript code, access the stated element by specifying the href attribute against it partially using the “document.querySelectorAll()” method.
- Finally, display the corresponding element, i.e., “<a>” against the specified partial attribute.
Output
The above output signifies that the stated element is fetched properly by partially specifying the href attribute.
Conclusion
The “document.querySelectorAll()” method can be implemented to get an element by specifying full or partial “href” attributes using JavaScript. This method can be utilized to fetch the element with the help of the contained href attribute in it. The same functionality can be performed by specifying the partial href attribute as well. This blog explained to get an element by href attribute in JavaScript.