`let html
function display(array){
tasksList.innerHTML = ''
html = ''
array.forEach(elm=>{
html += `<li>
<span id="${elm.id}" class="${elm.class}">${elm.title}</span>
<p >${elm.desc}</p>
<div>
<button id="${elm.id}" class="done-task">Done</button>
<button id="${elm.id}" class="delete-task">Delete</button>
<button id="${elm.id}" class="edit-task">Edit</button>
</div>
</li>`
tasksList.innerHTML = html
})
}
tasksList.addEventListener('click', (e)=>{
if(e.target.tagName == 'SPAN'){
console.log(e.target.nextElementSibling.tagName)
e.target.nextElementSibling.classList.toggle('desc')
e.target.style.color = 'red'
console.log('Changed color to red for', e.target.nextElementSibling);
}
})
this is the only css related to that part:
#tasks-list li span{
cursor: pointer;
}
/* #tasks-list li p{
display: none;
} */
.desc{
display: none;
}`
in the console it states that the nextElementSibling is actually adding the class and the style but in the same time in the DOM it doesn’t.
I have tried adding the class manually to the
and it did hide the element.
I tried console logging the targetElement and to console log its sibling and indeed they both return to be the span and the p.
Iss Ayy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
The issue is likely how the innerHTML updates are happening during the forEach loop. Each iteration overwrites the entire content, which can interfere with event listeners and DOM state. Try this fix:
let html = '';
function display(array) {
// Build HTML string once
html = array.map(elm => `
<li>
<span id="${elm.id}" class="${elm.class}">${elm.title}</span>
<p>${elm.desc}</p>
<div>
<button id="${elm.id}" class="done-task">Done</button>
<button id="${elm.id}" class="delete-task">Delete</button>
<button id="${elm.id}" class="edit-task">Edit</button>
</div>
</li>
`).join('');
// Update DOM once
tasksList.innerHTML = html;
}
tasksList.addEventListener('click', (e) => {
if (e.target.tagName === 'SPAN') {
const desc = e.target.nextElementSibling;
desc.classList.toggle('desc');
e.target.style.color = 'red';
}
});
I used array.map()
instead of forEach to build HTML and moved innerHTML update outside the loop. Also simplified event listener logic
This should resolve the issues you’re experiencing.