I need to make reservation system for test with HTML, CSS, JS. i need to change color of border from li’s. But i need to select only one li if i select one it must be add class, when i click to other one it need to delete class from first li.
const staff = [
{
"id": 1,
"name": "Alex Rosetta",
"email": "[email protected]",
"image": "https://i.ibb.co/LJnNhRF/unsplash-279x-IHym-PYY.png",
},
{
"id": 2,
"name": "Maria July",
"email": "[email protected]",
"image": "https://i.ibb.co/3FhkswY/unsplash-IF9-TK5-Uy-KI.png",
}
];
staff.map(({ id, name, email, image }) => {
const list = document.querySelector('.myUl');
list.innerHTML += `<li class="repoFolder" data-value="${id}">
<div class="doc-photo">
<img src="${image}" />
</div>
<div class="doc-infos">
<p class="name">${name}</p>
<p class="mail">${email}</p>
</div>
</li>`;
});
var items = document.querySelectorAll(".myUl li");
var tab = [], index;
// function rootFolder() {
// alert(items.getAttribute('data-value'));
// }
// for (var i = 0; i < items.length; i++) {
// items[i].onclick = function (e) {
// alert(e.getAttribute('data-value'));
// };
// }
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
console.log(this.getAttribute('data-value'));
if (this.classList.contains('my-class')) {
this.classList.remove('my-class');
} else {
this.classList.add('my-class');
}
};
}
i tried this, but didnt work
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
console.log(this.getAttribute('data-value'));
if (document.querySelector(".myUl li").classList.contains('my-class')) {
document.querySelector(".myUl li").classList.remove('my-class');
this.classList.add('my-class');
} else {
this.classList.add('my-class');
}
};
}
Can someone help please?
Thanks!
2
Answers
You can use
toggle
instead ofadd
andremove
. As second argument you can pass a boolean: let it be true when the iterated item is the clicked one:Not related, but don’t use
.map
for iteration when you don’t use its return value. Then use.forEach
.map
returns a new array of transformed elements. Since you’re also working with template strings you may as well use that to your advantage.map
over the data and return a new (joined) array of HTML strings, and join that up into one HTML string. You can useinsertAdjacentHTML
to add that to the list element.The next step is to use event delegation – attach one listener to the list element and have that watch for events as they bubble up the DOM from its child elements (ie its list items).
Once it catches an event it first checks that the event occurred within a list item, removes the "active" class from all the list items, and then adds one to the item that fired the event.