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.

1 Answers

3
Maheer Ali On

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

})