-1

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

Mehdi
  • 1
  • 2
  • You can try something like this: document.getElementsByClassName('grid')[5].getElementsByTagName('a')[0].href – Scotty Jamison Jun 15 '21 at 23:47
  • Does this answer your question? [Get local href value from anchor (a) tag](https://stackoverflow.com/questions/15439853/get-local-href-value-from-anchor-a-tag) – dale landry Jun 15 '21 at 23:58

3 Answers3

1

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

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

Kinta
  • 57
  • 1
  • 6
0

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.

Aviral
  • 218
  • 2
  • 12