Maarten Wolfsen Maarten Wolfsen - 1 year ago 63
HTML Question

Check if array contains certain string, then select that item

Okay, this might sound very vague, but I will try to explain best I can.

I have an image, and I collected its source with the

function. This image is one of 5 other images, all in the same div. So far I have collected two things:

  1. var src, which contains the url of the image I clicked.

  2. var array, an array which contains all of the images in the div.

Here is the HTML structure:

<div class="images">
<img src="path1" />
<img src="path2" />
<img src="path3" />
<img src="path4" />
<img src="path5" />

Imagine, I clicked the third image. The variable 'src' will contain the value 'path3'. I want, when I click on an arrow icon I have at the bottom of my page, that the value will be switched to 'path2', the previous item in the array.

How do I do this?

Answer Source

Assuming your variables src and array:

var index = array.findIndex(function(img) {
    return img.src === src

var elementYouWant = array[index - 1]

You may add a check if index is zero, because in that case index - 1 would be -1 and elementYouWant will be undefined. Same for array.length

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download