jquerycustom-data-attributejquery-data

Get each numbered data attribute jquery


HTML

<figure class="video-thumb" 
  data-thumb-0="image2.jpg" 
  data-thumb-1="image3.jpg"
  data-thumb-2="image4.jpg"
  data-thumb-3="image5.jpg"
> 
  <img src="image1.jpg"> 
</figure>

I want to get each of these data-thumb-* attributes with jQuery.

I then want to iterate through these using setInterval to swap the src of image1.jpg.

I will end up with the user hovering and seeing the data-thumb-0/1/2/3/4/etc, over the duration of a few seconds.

The reason I have these numbered (data-thumb-0/1/2/3/4/5) is because the CMS pushes these numbers out based on how many thumbs the client has uploaded.

I hope this is enough information, any help seriously appreciated.


Solution

  • Assuming you have your element in a variable such as elem, try this:

    var thumbs = [], i = 0, attr;
    while( attr = elem.getAttribute("data-thumb-"+i)) {
        thumbs[i] = attr;
        i++;
    }
    

    This will give you an array of thumbnails.