简体   繁体   中英

select grand children elements

I'm struggling to select my img Element in a list so i can switch its class on and off. I've tried different way to select it but its the first picture of my list that lights up, even when mouseover on the second/third/... div of the list.

<ul>
  <li>
    <div class="container" onmouseover="toggleImgColor()" onmouseout="toggleImgColor()">
      <div class="container-title">
        <h3 class="title />
        <img id="pic" class="greyImg" />
      </div>
      ...
    </div>
  </li>
  ...
</ul>

Javascript

function toggleImgColor() {
  $(this).find("img").toggleClass("greyImg");
}

You can do that something like this:

$(document).ready(function(){
   $(".container").hover(function() {
      $("#pic").toggleClass("greyImg");
   });
});

Just pass this inside the toggleImgColor() in html like toggleImgColor(this) , and catch that as parameter in javascript function. This will pass current hovered DOM object to toggleImgColor function and you can then use that to show that specific div.

HTML:

<ul>
  <li>
    <div class="container" onmouseover="toggleImgColor(this)" onmouseout="toggleImgColor(this)">
      <div class="container-title">
        <h3 class="title />
        <img class="greyImg" />
      </div>
      ...
    </div>
  </li>
  ...
</ul>

JavaScript:

function toggleImgColor(item) {
  $(item).find("img").toggleClass("greyImg");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM