As you can see I'm creating that html part with js, but after I generated the 'nav_list-item' class I can't access to it later. I want to add an active class to the 'nav_list-item'
const navItems = [
{
name: "Home",
link: "#",
icons: "fa-house",
class: "active"
},
{
name: "Projects",
link: "#project",
icons: "fa-briefcase",
class: ""
}
];
const nav_list = document.querySelector('.nav_list');
window.addEventListener('DOMContentLoaded', () => {
let displayNav = navItems.map((item) => {
return `
<li >
<a href="${item.link}" >${item.name}</a>
<a href="${item.link}" >
<i ></i>
</a>
</li>`;
}).join("");
nav_list.innerHTML = displayNav;
});
/* Add active state to nav */
const nav_lists = document.querySelectorAll('.nav_list-item');
nav_lists.forEach(e => {
e.addEventListener('click', () => {
nav_lists.forEach(e => e.classList.remove('active'));
e.classList.add('active');
});
});
CodePudding user response:
Just do it INSIDE load event.
Works for me
const nav_list = document.querySelector('.nav_list');
const navItems = [
{
class: 'class-1',
link: 'link-1',
icons: 'icon-1',
name: 'name-1'
},
{
class: 'class-2',
link: 'link-2',
icons: 'icon-2',
name: 'name-2'
},
{
class: 'class-3',
link: 'link-3',
icons: 'icon-3',
name: 'name-3'
}
]
window.addEventListener('DOMContentLoaded', () => {
let displayNav = navItems.map((item) => {
return `
<li >
<span href="${item.link}" >${item.name}</span>
<a href="${item.link}" >
<i ></i>
</a>
</li>`;
}).join("");
nav_list.innerHTML = displayNav;
const nav_lists = document.querySelectorAll('.nav_list-item');
nav_lists.forEach(e => {
e.addEventListener('click', (ev) => {
ev.preventDefault();
console.log(ev);
nav_lists.forEach(e => e.classList.remove('active'));
e.classList.add('active');
});
});
});