- JavaScript — get href attribute value via DOM traversal
- 4 Answers 4
- Edit
- Original Answer
- How to Get the Href of a Clicked Link in JavaScript
- Creating an Event Listener
- Retrieving the Href Attribute
- In Conclusion
- 1 comment
- Leave a comment Cancel reply
- Get href in JavaScript
- Get Href or Location in JavaScript
- Use getAttribute() to Get Href in JavaScript
- Use href Attribute to Get Href in JavaScript
- Related Article — JavaScript Href
JavaScript — get href attribute value via DOM traversal
I am writing a client-side JavaScript code and I have to retrieve the URL from the href attribute. I have already travelled the DOM to a point where:
document.getElementById('something').getElementsByTagName('td')[3];
From there, how do I get http://example.com ? I tried using .getAttribute(«href») , but I got null . Am I missing something?
I would say so you are missing something. Ever hear of a td (table cell), having a href attribute? No? Me either.
4 Answers 4
The td tag does not have href attribute (no table cell has this attribute); its child a tag does.
You can get the a tag inside the table cell with a query selector from which you can get the href attribute.
document.getElementById('something').getElementsByTagName('td')[3].querySelector('a').href;
Or you can combine the whole selection into a query selector.
document.querySelector('#something td:nth-child(3) a').href;
1 2 example.com
Edit
I think I should point out (since this has been accepted), what @LGSon had put in the comments and @hev1 has put in their answer, that this should be handled in a more elegant way than simply calling getElement on multiple DOM elements.
Here is a proposed (and much nicer) version of the call to get the href value:
document.querySelector('#something td:nth-child(3) a').href;
Original Answer
tdElement = document.getElementById('something').getElementsByTagName('td')[3]; anchor = tdElement.children[0]; anchor.getAttribute("href");
How to Get the Href of a Clicked Link in JavaScript
Learn how to get the href attribute of any, or specific, clicked links in JavaScript.
When the user clicks on a link in your HTML document, you want to retrieve the target URL, meaning the value of the href attribute, with JavaScript.
What is the best way to accomplish this?
To get the value of the href attribute of a clicked link, create an event listener using AddEventListener() and retrieve the value of the href attribute using Element.target() .
This tutorial will show you exactly how to do this in two steps.
First, you will learn how to create an event listener for all links or for specific links. Second, you will learn how to retrieve the value of the href attribute of a link when the user clicks it.
Creating an Event Listener
The EventTarget.AddEventListener() method of the EventTarget() Web API in JavaScript lets you create event listeners for when the user clicks on a DOM element in your HTML document.
This method lets you declare a function that gets called every time the event is fired. From the event, you can read the properties of the DOM element that it was attached to, allowing you to parse the value of the href attribute and store it in a variable.
The syntax for the AddEventListener() method is as follows:
// Event listener syntax EventTarget.AddEventListener(type, listener);
Both the type and the listener arguments are mandatory.
Type is a string that specifies the event type that you want the event listener to listen for.
Listener can be an object within the scope of the EventListener Web API, or a function that gets called every time the event is fired.
In this case, we need to create an event listener for clicks on link elements, meaning elements.
One of the best ways to do this is to use the Document.querySelectorAll() method. This method lets you create a loop that targets all instances of specific DOM elements using CSS selectors.
So you can do a simple selection for all links on your HTML page—or a narrowed-down selection of links with a specific id, class, or other.
Here’s how an event listener for all link clicks looks like:
// Create event listener for all link clicks document.querySelectorAll('a').forEach(link => link.addEventListener('click', (e) => console.log('A link was clicked'); >); >);
If you need to narrow down your event listener’s scope to clicks on specific links, for example links with a given id or className , all you need to do is modify your CSS selector:
// Event listener only for document.querySelectorAll('a.nav-item').forEach(link => link.addEventListener('click', (e) => console.log('A link was clicked'); >); >); // Event listener only for document.querySelectorAll('a#nav-item-01').forEach(link => link.addEventListener('click', (e) => console.log('A link was clicked'); >); >);
Depending on your implementation requirements, a CSS selector can be as simple as targeting elements or as complex as targeting an n-th element within a parent element or a group of elements.
Mastering CSS selectors can take your query selection skills to the next level. If you’re a frontend developer, this skill will give you an upper hand in your daily work.
Retrieving the Href Attribute
Now that you know how to create event listeners that listen to clicks on links, whether all links or specific links, let’s look at how to retrieve the value of the href attribute from them.
This can be done by passing on the e parameter to the function,short for “event,” that gets called on click.
Then, you can use the Event.target() Web API to retrieve the className attribute of the DOM object to which the event in your event listener was attached:
// Create event listener for all link clicks document.querySelectorAll('a').forEach(link => link.addEventListener('click', (e) => // Retrieve href and store in targetUrl variable let targetUrl = e.target.href; // Output value of targetUrl to console console.log('A link with target URL ' + targetUrl + 'was clicked'); >); >);
If you opened up your browser’s console right now, copy/pasted and ran this code, then clicked on a link or two, you’d observe the following results:
In Conclusion
I hope you found this tutorial useful.
I recently had to tackle this challenge myself as I implemented a data layer for analytics purposes on one of my websites. It took me a few tries (and a couple of hours) to get to the best solution, and I believe this is it.
If you have any questions, or you want to share other ways to achieve this with the rest of this post’s readers, be sure to leave a reply below.
1 comment
Greetings.
Just what I needed after several hours of trying with a multilevel menu. Excellent tutorial. Thank you very much, very grateful.
Leave a comment Cancel reply
- How to Wait for an Element to Exist in JavaScript July 13, 2023
- How to Check If a Function Exists in JavaScript July 13, 2023
- How to Remove Numbers From a String With RegEx July 13, 2023
- How to Check If a String Is a Number in JavaScript July 13, 2023
- How to Insert a Variable Into a String in PHP July 12, 2023
We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.
Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.
These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Get href in JavaScript
- Get Href or Location in JavaScript
- Use getAttribute() to Get Href in JavaScript
- Use href Attribute to Get Href in JavaScript
The article will teach how to get the href/location in JavaScript. The JavaScript widget offers two choices; the first uses the location attribute, and the second uses the open method.
Get Href or Location in JavaScript
The location interface represents the location (URL) of the object to which it is linked. The Document and Windows interfaces have an associated location that can be accessed via document.location or window.location .
The biggest difference between them is their browser compatibility. The window.location is read/written by all supported browsers.
The document.location is read-only in IE but read/write in Gecko-based browsers like Firefox.
To communicate with the browser, JavaScript provides the main window object. Represents the browser window.
All global variables and functions become members of the widget. The window position object is used to get the URL of the current page and also change the redirect URL.
Use getAttribute() to Get Href in JavaScript
The Element interface’s getAttribute() method returns the value of a specified attribute for the element. If the specified attribute does not exist, the return value is null or » » (the empty string).
const attributeOutput = element.getAttribute(attributeName);
The attributeName is the attribute’s name whose value you want to retrieve. It returns the string containing the value of attributeName .
Further information on the getAttribute function can be found in the documentation for the getAttribute .
a id="google" href="https://www.google.com">a> a id="local" href="aboutUs">a>
const value1 = document.getElementById("google").getAttribute("href"); const value2 = document.getElementById("local").getAttribute("href"); console.log(value1); console.log(value2);
In the above code, we use the element’s getAttribute method to fetch the value of a select attribute associated with the requested element. Once you run the above code in any browser, it’ll print something like this.
"https://www.google.com" "aboutUs"
Use href Attribute to Get Href in JavaScript
The HTMLAnchorElement.href property is a stringifier that returns a USVString containing the full URL and allows the href to be updated.
The sole difference between the getAttribute() and href attribute is that prior returns the value of the anchor element. In contrast, the latter returns the full path where the anchor element points.
// Getting href string = anchorElement.href; // Setting href anchorElement.href = string;
a id="google" href="https://www.google.com">a> a id="local" href="aboutUs">a>
const value1 = document.getElementById("google").href; const value2 = document.getElementById("local").href; console.log(value1); console.log(value2);
In the above code, we use the href attribute of the anchor element, which will give the full path where the anchor element points. Once you run the above code in any browser, it’ll print something like this.
"https://www.google.com/" "https://fiddle.jshell.net/_display/aboutUs"
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.