JustMe
JustMe

Reputation: 327

How to generate multiple a tags with JavaScript?

I would like to create multiple a tags to populate a div. Writing this in HTML would take a lot of rows and a JavaScript script would make things easier. Unfortunately, I'm still learning it and I'm looking for some help.

Below is my HTML code that I want generated using JavaScript, inside div id="countries"

<div class="countries">
  <div id="Denmark">
    <h4>Denmark</h4>
<!-- number of links is variable to each country -->
    <a href="https://www.example.com">Link1</a>
    <a href="https://www.example2.com">Link2</a>
  </div>
</div>

Some JS code

let countrySelect = document.getElementsByClassName('countries');

let links = ["https://www.example1.com", "https://www.example2.com", "https://www.example3.com", "https://www.example4.com", "https://www.example5.com", "https://www.example6.com", "https://www.example7.com", "https://www.example7.com"];

// make an array of countries
let countries = ["Denmark", "Spain", "Italy", "Slovenia", "Malta", "Hungary", "Austria", "Czech Republic"];

// make a div
let makeDiv = document.createElement("div");
// add an ID to div just created
makeDiv.setAttribute('id', 'country');
// make an A tag
let tag = document.createElement("a");
tag.setAttribute('href', links[1]); // multiple links needed...integrate in a loop?

// make a loop to create multiple country divs
for (let index = 0; index < countries.length; index++) {
  // insert all the elements in the loop
}

Upvotes: 0

Views: 1297

Answers (2)

Barmar
Barmar

Reputation: 781878

You need to create the a element and set its href and text in a loop.

countries.forEach(country => {
    let makeDiv = document.createElement("div");
    makeDiv.id = country;
    let h4 = document.createElement("h4");
    h4.innerText = country;
    makeDiv.appendChild(h4);

    links.forEach((link, i) => {
        let tag = document.createElement('a');
        tag.href = link;
        tag.innerText = `Link${i+1}`;
        makeDiv.appendChild(tag);
    });

    countrySelect[0].appendChild(makeDiv);
});

Upvotes: 2

ינון רחמים
ינון רחמים

Reputation: 706

a. yes, create a loop. you can use also countries.forEach(()=> ...) btw. b. dont forget to append the element before the loop continue. c. a little suggestion - if the code is getting bigger, divide your code to little funtions with meaningful name.

good luck!

Upvotes: 0

Related Questions