I am trying to loop through 2 arrays. The first array is the link name the second array is the links 'a' value. I want to loop through the two arrays attaching the value of the second array to the href of each link that is created / in the first array. This is what I have and it not working for me.
const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];
for (let i = 0; i < links.length; i++) {
for (let j = 0; j < hrefLinks.length; i++) {
if (links.length === hrefLinks.length) {
const li = document.createElement('li');
const liLink = document.createElement('a');
liLink.setAttribute('href', hrefLinks[i]);
liLink.className = 'Test-Class';
li.appendChild(liLink);
li.className = 'nav-link';
list.appendChild(li);
li.innerHTML += links[i];
}
}
}
I do have it working with one forEach loop but got confused on how I would nest the second forEach;
const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];
links.forEach(function (link) {
const li = document.createElement('li');
const liLink = document.createElement('a');
li.appendChild(liLink);
li.className = 'nav-link';
list.appendChild(li);
li.innerHTML += link;
});
Is this the proper way of doing this or is there an easier / cleaner way of doing this?
You don't want a nested loop - you simply need to link the i
th item in links
to the i
th item of hrefLinks
. With forEach
, you can do this just by using the second argument to the callback, which will refer to the current index being iterated over:
const list = document.body.appendChild(document.createElement('ul'));
const links = ['Home', 'Contact', 'About'];
const hrefLinks = ['/', 'contact', 'about'];
links.forEach((linkName, i) => {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = hrefLinks[i];
a.textContent = linkName;
li.appendChild(a);
li.className = 'nav-link';
list.appendChild(li);
});
create an objects array which holds the link name and url, then you can iterate that object for add the anchor elements into you dom, as follows
//an object which hold navigation url and name
var navLinks = [{
label: 'Home',
href: '/'
}, {
label: 'Contact',
href: 'contact'
}, {
label: 'About',
href: 'about'
}]
navLinks.forEach(function(link) {
var li = document.createElement('li');
li.className = 'nav-link';
var liLink = document.createElement('a');
var linkText = document.createTextNode(link.label);
liLink.appendChild(linkText);
liLink.className = 'Test-Class';
liLink.href = link.href;
li.appendChild(liLink);
document.body.appendChild(li)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With