Ways to find the image source using JavaScript/Jquery upon page loading?

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!

Answer №1

// It seems like you're not very clear about your intentions.
// You have typed a lot without providing any specific details or highlights.
// However, here are a few things I noticed:
  var arr = []; // This array will store all tags (like td) with the class '.home'
  if(arr[i].innerHTML.indexOf("Boston") != -1) { } // Using indexOf() on a DOM element won't work

// If arr[0] is a DOM element, why are you using .indexOf("Boston") on it?

// Next, $('.homeimage img') returns DOM elements with the class 'homeimage' or tagName 'img'
  $('img.homeimage'); // This might be what you intended to do.

// Let me provide you with an answer.
// The oImgUrl acts as a map from certain ((String))-->((img url))
  var oImgUrl = {
    'Boston': 'http://another.imageurl.com/boston.png',
    'NewYork': 'http://another.imageurl.com/newyork.png'
  };

// I have left your "arr" unchanged
// This will check every element in arr
// If it contains a String like 'Boston' or 'NewYork'
//   find the img tag (img.homeimage) within it
//   and assign the respective URL string to the img tag
  for (var i=0, length=arr.length; i < length; i++) {
    if(arr[i].innerHTML.indexOf("Boston") != -1) {
      arr[i].find('img.homeimage').attr('src', oImgUrl['Boston']);
      continue;
    } 
    if(arr[i].innerHTML.indexOf("New York") != -1) {
      arr[i].find('img.homeimage').attr('src', oImgUrl['NewYork']);
      continue;
    } 
  }

Example HTML:

<td class='home'>Welcome to Boston!<img class='homeimage'></td>
<td class='home'>Welcome to New York!<img class='homeimage'></td>

Answers:

Question 1: Custom ID?
JavaScript will identify these two td.home elements and add them to arr.
Then, different image URLs will be applied to the img tag
based on the innerHTML of the td tag.
You don't need to assign each img tag a unique ID.
Question 2: Script placement below HTML?
No, it's not necessary.
Keep these scripts wrapped inside a document ready function.
Therefore, they will only execute when the HTML DOM is fully loaded.
In other words, regardless of where you position this script,
it will run after all Tags are ready.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing JavaScript Variables Through Dynamic Ajax/PHP Interaction

I've been encountering some difficulties when trying to refresh my game. Initially, I attempted echoing the entire script each time... but that method was not aesthetically pleasing. Currently, I am experimenting with updating the variables through an ...

Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to mainta ...

Unable to interpret the remainder: '('static', filename='main.png')' within the context of 'url_for('static', filename='main.png')'

I am a beginner with django and I'm attempting to display an html page. I have a test HTML page and a URL for testing purposes. When accessing the URL, I encounter the following error: Could not parse the remainder: '('static', filena ...

Having trouble retrieving data from the json file

Using Ajax to obtain a JSON update: $(document).ready(function(){ $('form').submit(function(event){ event.preventDefault(); var form = JSON.stringify($('form').serializeArray()); $.ajax ({ u ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

Divider displayed between images in Internet Explorer 8

On my website, I have arranged four images in a square using the code below: <div id="tempo_main"> <div id="tempo_content"> <div style="text-align: center;z-index: 3;position: absolute;right:350px; left:350px; t ...

What sets PHP fsockopen apart from WebSockets in HTML5?

Are there differences between server-side and client-side processing? Is it possible to send instant messages using PHP's fsockopen, or am I restricted to using JavaScript for polling on the client side? ...

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

Updating the style of a CSS element using Python Selenium

Is it possible to change the css element style using Python Selenium during automation to increase the height of the page? The structure of the element in the HTML is as shown below: <div style="overflow-y:scroll;overflow-x:hidden;height:150px;&quo ...

Exporting data from a jQuery table to CSV format

I have customized the jQuery Table to CSV Plugin so that it triggers a browser download of a CSV file. The original function was: function popup(data) { var generator = window.open('', 'csv', 'height=400,width=600'); ge ...

Creating a like and dislike button using Jquery's ajax functionality

Hey everyone, I'm currently working on implementing a like and dislike button similar to Facebook's on my website. I have a list of posts displayed using PHP loops and I want a single button to change color to blue if liked and remain the default ...

Removing Additional Parameters from the Delete URL in jqGrid

I'm currently working on adding delete, update, and add functionality to my grid. The problem I'm facing is that when I submit the delete confirmation popup, the URL ends up with extra parameters that I want to remove. For example: I want it to ...

Verification of javascript for an unpredictable image generator script

When running the W3C Validation tool, an error is returned stating 'img not acceptable here.' Any suggestions on how to resolve this issue? <script type="text/javascript" language="JavaScript"> NumberOfImagesToRotate = 9; FirstPart = &ap ...

Tips for minimizing unnecessary rerenders in child components that rely on cached information from the parent component

check out the sandbox here Application maintains state to compute a memoized value, which is then passed as props to the Options. When a change occurs in the state triggered by a callback function in Option, it causes a rerender of the main Application, r ...

Tips for accessing a DOM element's ::before content using JavaScript

Is there a way to retrieve the content of a DOM element's ::before pseudo-element that was applied using CSS3? I've attempted several methods without success, and I'm feeling very confused! // https://rollbar.com/docs/ const links = docum ...

Is it possible to display multiple qTips for the same target using jQuery qTip2?

I am currently utilizing the jquery qtip2 plugin to generate a mouseover tooltip. Here is the code snippet I am using: $(document).ready(function() { $("#optionalProdsImgPreview_1").qtip({ content: "<img src='http://mysite.com/myimg.jpg&ap ...

Eliminate the need for pressing the "tab" key on my website

I'm currently working on a horizontal web page layout and I'm looking for a way to disable the "tab" button functionality on my page. The issue arises because I have a contact form with textboxes located in the last div, and when users navigate u ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

Issues with the plugin for resizing text to fit the parent div's scale

I've spent the last hour attempting to get this script to function properly, but no luck yet. Check out the correct jsfiddle example here: http://jsfiddle.net/zachleat/WzN6d/ My website where the malfunctioning code resides can be found here: I&apo ...

Incapable of utilizing CSS Custom Properties (also known as CSS Variables) in conjunction with SASS @if Conditional Statements

I'm attempting to transfer CSS Custom Properties to a SASS Mixin. I can successfully use the variables directly in the desired styling. However, there seems to be a problem when utilizing a variable within an If statement. Here's an example of t ...