I have a collection of images displayed in div tags with data attributes. My goal is to toggle their visibility using CSS based on a match with input text. I iterate through the divs with the matching class, then loop through the words in the input array, and finally, through the words in the data attribute field. The issue arises when the DOM seems to lose track of the outer index once a match is found between the inner array text values. Although the console correctly identifies the three loop index values, the JavaScript show command doesn't get executed. When I hard code the index value (0), the show command works as expected, but this approach seems overly convoluted.
HTML:
<img
src="images/game thumb 216px-1.png"
alt="Photo of hotline game"
class="gallery__photo photo1"
/>
</div>
<div
class="gallery__item"
data-new="true"
data-top="true"
data-value="2 neon jungle"
>
<img
src="images/game thumb 216px-2.png"
alt="Photo of neon jungle game"
class="gallery__photo photo2"
/>
</div>
JavaScript/jQuery:
//building an object containing all gallery__item divs
//let galleryitems = document.getElementsByClassName("gallery__item");
//assigning search input words to a variable
let myInputWords = $("#search").val();
//creating an array of input words
let myInputWordsArray = myInputWords.split(" ");
//creating an array of gallery words
let myGalleryItemsArray = [];
for (let i = 0; i < galleryitems.length; i++) {
//fetching the data-value attribute value
let myAttributeValue = galleryitems[i].getAttribute("data-value");
//adding it to the gallery item array
myGalleryItemsArray.push(myAttributeValue);
}
//iterating through the input words array - outer loop
//iterating through the gallery words array - inner loop
let i, k, m = 0;
//iterate through the input element words array
for (i = 0; i < myInputWordsArray.length; i++) {
//loop through gallery items array
for ( k = 0; k < myGalleryItemsArray.length; k++) {
//loop through each gallery item which may contain multiple words and create a new array
let myGalleryItemArray = myGalleryItemsArray[k].split(" ");
//iterating through each element in the gallery item array's words
for ( m = 0; m < myGalleryItemArray.length; m++) {
//console.log(myInputWordsArray[i]);
//console.log(myGalleryItemArray[m]);
//if the outer input array word matches the inner data word, change the CSS display to block; else, set it to none
if (myInputWordsArray[i] === myGalleryItemArray[m]) {
galleryitems[k].style.display = "block";
//console.log(galleryitems[k]);
} else {
galleryitems[k].style.display = "none";
}
}
}
}
});