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?
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>
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;
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With