How To Select The N-th Picture In Javascript

- 1 answer

I am trying to change the some code in Javascript for my Shopify store, what I am trying to do is when a color option of a product is selected, the featured images changes to the second or third image of the variant (each variant has 5 images), right now, as you can see from the code, it only changes to the Featured image, I would appreciate it if you can help me on this, thanks in advance!

     * Trigger event when variant image changes
     * @param  {object} variant - Currently selected variant
     * @return {event}  variantImageChange
    _updateImages: function(variant) {
      var variantImage = variant.featured_image || {};
      var currentVariantImage = this.currentVariant.featured_image || {};

      if (!variant.featured_image || variantImage.src === currentVariantImage.src) {

        type: 'variantImageChange',
        variant: variant



If you know exactly which image you need just based on array positioning, the code would be pretty simple:

var all_images = document.querySelectorAll(some_css_selector_string);
var image_i_want = all_images[some_index];

The hard part is knowing which array index you want - and the featured image on each variant (if you've set up featured images on each variant individually) should be giving you the correct image information. (You might also want to double-check your product in the Shopify admin to make sure that each individual variant has an appropriate image set) If this is still not working, you might want to add a to that code so that you can inspect the available information so that you can make meaningful decisions based on what the variant actually represents.

For example, if your image naming scheme is consistent with the names of the options of the variants, you could use the values in variant.option1 / variant.option2 / variant.option3 to assemble the expected image name and update the image tag based on that.

(BTW: The code that's actually updating your image is probably in a function that's listening for the 'variantImageChange' event - the code you've provided isn't directly changing anything on the page)

Hope this helps!