2

I have a task that is to create links on navigation list's "li" elements and its text. So I have to add a anchor element with a href attribut to three li elements with class="navigation". I tried to do a code to this, but it's not correct can anyone help me to make it work.

var a = document.createElement("a");
var li = document.getElementsByClassName("navigation");
for (i = 0; i < a.length; i++) {
a.setAttribute("href", "#html");
li.appendChild(a);
}

li class = "navigation" - should be changed to be - li class = "navigation" a href="#HTML" and so on for the three "li" elements.

Sus
  • 63
  • 6

1 Answers1

3

In you code a is declared only once and when when you change setAttribute and append a to li a will refer to the same element.

  • Move the declaration of a inside the for loop.
  • Use li[i] instead of li because li is not element its HTMLCollection.

Also add some innerHTML to a so see if its present.And avoid declaring implicit globals. Use let with i.

var li = document.getElementsByClassName("navigation");
for (let i = 0; i < li.length; i++) {
   var a = document.createElement("a");
   a.setAttribute("href", "#html");
   a.innerHTML = 'link' + i
   li[i].appendChild(a);
}

I would suggest you using querySelectorAll and forEach loop.

var li = document.querySelectorAll(".navigation");
li.forEach(x => {
  var a = document.createElement("a");
  a.setAttribute("href", "#html");
  a.innerHTML = 'link' + i
  x.appendChild(a);

})
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • @MattEllen Thanks for suggestion. I have edited the answer. – Maheer Ali May 01 '19 at 08:51
  • There is a typo in the first code, `for (let i = 0; i < li.length; i++) {` `a.length` should be `li.length` – Romain May 01 '19 at 08:59
  • Great code, this worked. Thank you! But now I have another problem. The navigation is not a link but instead there is a link next to the navigation headline. – Sus May 01 '19 at 09:08
  • @Sus Can't say anything without seeing the code you are using. – Maheer Ali May 01 '19 at 09:09
  • The HTML code is
  • And the result on the page is - HTMLlink0 DOMlink1 Javasscriptlink2 – Sus May 01 '19 at 09:26
  • @Sus If you want to remove `HTML,...` then use `li[i].innerHTML = ''` in the start of loop. – Maheer Ali May 01 '19 at 14:11