Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];

Which outputs:

<td><a href="http://example.com"></a></td>

From there, how do I get http://example.com?

I tried using .getAttribute("href"), but I got null.

Am I missing something?

like image 497
hnvasa Avatar asked Sep 17 '25 01:09

hnvasa


2 Answers

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;

<table id="something">
<td>1</td><td>2</td><td><a href="http://www.example.com">example.com</a></td>
</table>
<script>
console.log(document.querySelector('#something td:nth-child(3) a').href);
</script>
like image 125
Unmitigated Avatar answered Sep 19 '25 15:09

Unmitigated


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

The href property exists on the anchor tag (<a>) which is a child of the <td> element. You will need to grab the anchor by using something like the DOM children property like so:

tdElement = document.getElementById('something').getElementsByTagName('td')[3];
anchor = tdElement.children[0];
anchor.getAttribute("href");
like image 35
Tim Klein Avatar answered Sep 19 '25 15:09

Tim Klein