Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading