Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the hover class working on the wrong element?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading