How to create more than one hyperlink html using a for loop? (for a Chrome extension)

function createDropDown(){
  const tree = document.createDocumentFragment();
  const link = document.createElement('a');
  for(let index = 0; index < urlList.length; index++){
    link.appendChild(document.createTextNode(urlList[index]));
    link.setAttribute("href", urlList[index])
    link.setAttribute("id", "link "+index)
    tree.appendChild(link);
    document.getElementById("hyperlinks").appendChild(tree);

This is my code, I am fairly new to JS and HTML. My goal is to have a hard-coded div with the id of hyperlinks. In this div, I want to put multiple hyperlinks for the length of the ‘urlList’ variable(an array of URLs).

The result I am getting is the insertion of one hyperlink that contains all URLs as text. The link associated with the hyperlink also happens to be the last URL in the urlList variable. Thanks.

>Solution :

Problem

You are configuring the same object in every iteration

Solution

Create new object in each iteration

for(let index = 0; index < urlList.length; index++){
  const tree = document.createDocumentFragment();
  const link = document.createElement('a');
  link.appendChild(document.createTextNode(urlList[index]));
  link.setAttribute("href", urlList[index])
  link.setAttribute("id", "link "+index)
  tree.appendChild(link);
  document.getElementById("hyperlinks").appendChild(tree);

Leave a Reply