Home > OS >  Why is the hover class working on the wrong element?
Why is the hover class working on the wrong element?

Time:07-24

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 >
            <p>${post.title}</p>
            <p >hover</p>
          </div>`
      )
    })
  })()
.post {
  border: 1px solid #000;
  margin-bottom: 15px;
}

.hidden {
  display: none;
}

.post:hover .post .hidden {
  display: block;
}
<div ></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.

CodePudding user response:

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 >
  Hello, world! <span >Hover text!</span>
</p>
<div >
  <p>Lorem ipsum</p>
  <p >Sample text!</p>
</div>

CodePudding user response:

.post .hidden means: the next .post .hidden. So make it .post:hover > .hidden

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 >
        <p>${post.title}</p>
        <p >hover</p>
      </div>`
    )
  })
})();
body {
  font: 1rem/1.3rem normal verdana, sans-serif;
  margin: 2rem;
}

.post {
  border: 1px solid #000;
  margin-bottom: 15px;
  cursor: pointer;
}

.post p {
  margin: 0.1rem 0.4rem;
}

.hidden {
  display: none;
}

/*Demo*/
.post:hover .post .hidden {
  display: block;
}

.post:hover .post .hidden:before {
  color: red;
  font-weight: bold;
  content: '.post:hover .post .hidden ';
}

.post:hover>.hidden {
  display: block;
}

.post:hover>.hidden:before {
  color: red;
  font-weight: bold;
  content: '.post:hover>.hidden ';
}
<div ></div>

  • Related