I wrote a code javascript code that will display the complete write up of a particular text which happens to be in three location in my html, but instead of displaying just the particular one that was clicked, its displaying others along codepen side. code screen shot
i was trying to make an hidden text non hidden upon clicking of the read more with bold print for individaul read me. check right side of my screen shot for the result
const readMore = document.querySelectorAll('.readMore')
const contents = document.querySelectorAll('.moreRead')
// const content = document.querySelector('.moreRead')
readMore.forEach((read, index) => {
read.addEventListener('click', (e) => {
console.log(e);
console.log(index);
read.classList.add('d-none');
// content.classList.remove('d-none')
contents.forEach(content =>{
content.classList.remove('d-none')
})
})
})
2
Answers
The issue is because when any one of
.readMore
are clicked you loop over every.moreRead
and display them – not only the one which is related to the clicked element.To fix this, you can use
parentElement
andquerySelector()
to target the sibling of the clicked.readMore
and updated its class:What I have understood about what you’re trying to do;
You have three sections each with a read more button to toggle that section’s visibility on or off.
However in your toggle buttons click event listeners, you turn on the visibility of all the collapsible sections by removing the d-none class. What you should instead do is remove the d-none class from only the section the toggle button controls.