简体   繁体   中英

How can I set an attributes (base on child attributes) in jQuery or JavaScript?

I want to set an attribute on hover, based on his child attributes, by using jQuery. I have tried many ways to make this, but no luck. All attributes are same and not changing on hover.

<li class="menu-item">
  <a data-src="" class="menu-item-link" href="#">Item one</a>
  <span class="description">
    <img  src="https://i.ibb.co/LxSKFgH/image1.jpg">
  </span>
</li>

<li class="menu-item">
  <a data-src="" class="menu-item-link" href="#">Item two</a>
  <span class="description">
    <img src="https://i.ibb.co/TLJL7hq/image2.jpg">
  </span>
</li>

What I want is when I hover on .menu-item I want to set .description 's img attribute on data-src attribute for each menu. That means Attribute must set on his parent attribute.

You can achieve what you want by executing the following jQuery script:

$(".menu-item").hover(function(){
   //Take the src value from the inner img tag
   let srcValue = ($(this).find("img").attr("src"));
   //Set the data-src attribute of the inner anchor tag
   $(this).find("a").attr("data-src", srcValue);
});

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