简体   繁体   中英

how to get the href value of a div using javascript

when i input the command

document.getElementsByClassName('grid')[5] :

i get this: TEST

HOwever i struggle finding how to get the href value (a link here), i have thought about using GetAttribute but it does no work

That's because you're selecting the <div> parent instead of <a> , div's doesn't have href attribute.

You can get the href by doing:

const $parentDiv = document.querySelectorAll('.grid')[5];
const $anchor = $parentDiv.querySelector('a');
console.log($anchor.href);

You can use children property to get the tag, and get the href thereafter

There are 2 ways how you can do that

1 -

You can add an id attribute to the <a> tag and then use document.getElementById("yourid").getAttribute("href");

2 =

As mentioned by Eliabe Franca -

 const $parentDiv = document.querySelectorAll('.grid')[5]; const $anchor = $parentDiv.querySelector('a'); console.log($anchor.href);

What this does is that it first gets the .grid[5] element and then gets the first <a> in it. The last line will help you get the href value.

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