1

I'm not really sure what I'm doing incorrectly here. The question asks us to Set the href attribute of the a tag to https://www.zybooks.com/.

This is the given tag <a href = "https://www.example.org>Link</a>

Here is my answer:

var x;
x = document.getElementsByTagName("a").href = "https://www.zybooks.com/";

The following error is given:

Testing the value of the href attribute Yours and expected differ. See highlights below. Yours https://www.example.org/ Expected https://www.zybooks.com/

I'm not sure why this is incorrect.

trenz
  • 25
  • 3

1 Answers1

0

The function getElementsByTagName returns a list of DOM elements, not just one!

So, simply accessing the list's first element with [0] should do the trick:

x = document.getElementsByTagName("a")[0].href = "https://www.zybooks.com/";

Edit: This answer just shows what was wrong in the OP's original code. As the comments say, using getElementsByTagName('a')[0] is definitely not the best approach; using querySelector("a") would be a better way to do it.

Anis R.
  • 6,656
  • 2
  • 15
  • 37
  • Thank you. This was correct. How would you access that element without using getElementsByTagName since there is no given ID in the tag? In other words, is there a way to access it without having [0] as part of the solution since it returns a list? – trenz Oct 26 '19 at 19:05
  • 1
    @trenz You can use `document.querySelector('a')`. This function takes regular CSS selectors and returns the first element that is a match. – Anis R. Oct 26 '19 at 19:07
  • @ScottMarcus I was just explaining what was wrong in the OP's statement, not saying this is the best approach. `querySelector` is a **much** better way to go indeed. – Anis R. Oct 26 '19 at 19:12
  • The longer the programming community continues to show inline scripting and the use of legacy API's, the longer we'll have to continue to answer these kinds of questions. The real answer here is "Your approaching this incorrectly. Here's the correct way to do it." – Scott Marcus Oct 26 '19 at 19:15