const fetchData = async() => {
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const data = await res.json()
return data
}
(async() => {
const container = document.querySelector('.container')
const data = await fetchData()
data.forEach(post => {
container.insertAdjacentHTML(
'afterend',
`<div class="post">
<p>${post.title}</p>
<p class="hidden">hover</p>
</div>`
)
})
})()
.post {
border: 1px solid #000;
margin-bottom: 15px;
}
.hidden {
display: none;
}
.post:hover+.post .hidden {
display: block;
}
<div class="container"></div>
Hello everyone, I am working on a project where I get data from an API and insert it into the DOM. Each piece of data has a .hidden element that is by default hidden using display: none. I want to be able to hover on each .post element and have .hidden in that element become visible. Currently, when I hover on a .post element, the .hidden in the next post element becomes visible not the one in the current element.
>Solution :
You’re using the CSS adjacent sibling combinator (+). Instead, use the child combinator (>), like so:
.post:hover > .hidden {
display: block;
}
.hidden {
display: none;
}
.post:hover > .hidden {
display: initial;
}
<p class="post">
Hello, world! <span class="hidden">Hover text!</span>
</p>
<div class="post">
<p>Lorem ipsum</p>
<p class="hidden">Sample text!</p>
</div>