I've scoured countless forums, yet a viable solution still eludes me.
My objective is simple - upon page load, I want to gather all elements with the ".home" class and store them in an array called arr. Subsequently, the script should iterate through each element in the array and compare it against a specific string. For instance, my current code checks if the element contains the word "Boston", then assigns a corresponding imgur link as the image source for elements with the ".homeimage" class. While I understand the implications of hosting images on imgur, I am merely testing functionality at this stage. Following this test code, there is some redundant code involving changing text color to gray, inspired by a similar example found on a forum thread, which led me to believe that manipulating attributes follows a similar pattern.
Here is a snippet of my HTML:
<td colspan = "3" width=400px class = "home"><b><%= game.home %></b></td>
<td colspan = "3"><img style="width:150px;height:128px;" class = "homeimage"></td>
This is how my JavaScript/jQuery code looks like:
<script> var arr=[]; $(document).ready( function(){ $(".home").each(function(){ arr.push($(this)); }); for(i = 0; i < arr.length; i++){ if(arr[i].indexOf("Boston") != -1){ $('.homeimage img').attr("src", "http://i.imgur.com/s5WKBjy.png"); } } $.each(arr, function(key, val){ val.css('color', 'gray'); }); //testing out something redundant }); </script>
Further inquiries:
In cases where there are multiple images with the ".homeimage" class and several checks for image sources, will all images within the class be assigned the src of the last checked image? To avoid this, would assigning a unique custom id instead of a class to each div be a suitable solution? Also, does the placement of this script relative to the HTML elements matter?
Grateful for any forthcoming advice or suggestions. Thank you!