简体   繁体   中英

Getting second and third elements out of an ordered list using jQuery

We are trying to add a class and change the URL of the image of the second and third elements in an ordered list using jQuery. The ordered list cannot be changed into unordered list. We need a way to select two items to add the class or change the image.

<div class= "image-gallery"> 

 <ol class ="image-control image-flex-control">

  <li> <img src="URL"> </li>
  
  <li> <img src="URL1"> </li>
  
  <li> <img src="URL2"> </li>

 </ol>

</div>

We need to change the src of second and third item only. How can we select the second and third using jQuery.

You can do this with .slice() in foreach.

Note: .slice() start from 0 (zero).

 $("li img").slice(1).each((key,val) => { $(val).attr('src','IMAGE URL') })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class= "image-gallery"> <ol class ="image-control image-flex-control"> <li> <img src="URL"> </li> <li> <img src="URL1"> </li> <li> <img src="URL2"> </li> </ol> </div>

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