0

So I have an Element Array retrieved using this line of code:

var listItems = ul[0].getElementsByTagName("li")



The output of

console.log(listItems[0].innerHTML)

gives me

<a class="view" href="https://www.notarealwebsite.com">See this cool link!</a>



How can I retrieve only the link (https://www.notarealwebsite.com) using pure Javascript?

I have tried the getAttribute("href") function to no avail.

Thanks!

  • You'll want to show how you were using `getAttribute` and it wasn't working, because that's literally the answer to your question. See [this duplicate question and its answers](https://stackoverflow.com/q/1550901/215552). – Heretic Monkey Feb 12 '18 at 01:42

1 Answers1

0

A straight-forward way to do this would be to get the a element inside of the li element, then access the href property off of that.

// using querySelector
const link = listItems[0].querySelector('a')

// or, using getElementsByTagName
const link = listItems[0].getElementsByTagName('a')[0]

console.log(link.href)

https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

kingdaro
  • 11,528
  • 3
  • 34
  • 38