简体   繁体   中英

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?

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> 

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");

Purely using js (not jquery ) and if you want to specifically continue from when you have selected the td tag you desire:

td.getElementsByTagName("a")[0].href

td being the td element that was returned from your example code.

<script>
let x = document.getElementById("test").href;
console.log(x);
</script>

You can also get by class or tag but you will have to loop through the array, and that could be a lot of tags on a page.

also,

document.getElementById('something').getElementsByTagName('td')[3].firstElementChild.href

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM