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

The difference between calling a function in the window.onload and in the body of a

In this HTML code snippet, I am trying to display the Colorado state flag using a canvas. However, I noticed that in order for the flag to be drawn correctly, I had to move certain lines of code from the window.onload() function to the drawLogo() function. ...

Tips for postponing the first button event in Vue 3 and JavaScript

My current task involves setting up a button event in Vue 3 that triggers a setTimeout countdown on the button before redirecting to another page. The event function has a conditional statement that initiates a countdown from 5 to 0 as long as the countVal ...

I developed a compact application utilizing Node.js in tandem with Express framework

There is an issue with the GPA calculator app built using Node.js and Express. It works fine for a single user, but when multiple users try to use it simultaneously, the scores are being combined, resulting in incorrect values. I need to create an app that ...

Can you guide me on implementing AWS SDK interfaces in TypeScript?

Attempting to create an SES TypeScript client using AWS definitions file downloaded from this link My approach so far: /// <reference path="../typings/aws-sdk.d.ts" /> var AWS = require('aws-sdk'); var ses:SES = new AWS.SES(); The error ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

What is the best way to execute tests in different environments with Protractor?

Is it possible to execute specifications in various environments? Maybe by adjusting the protractor-config file? Could we do something along the lines of specs: ['../tests/*.js', server1], ['../more_tests/*.js', server2] within the ...

Steps to record and upload a video directly to the server using getusermedia

For my application, I need the user to record a video and have it saved on the server disk instead of downloading it to the client browser. I am currently using getusermedia for this purpose, with the following code: (function(exports) { exports.URL = exp ...

Tips for organizing an AngularJS bootstrap Modal for a search feature

I need help with integrating AngularJs, bootstrap, and an API to populate a bootstrap modal popover with JSON data upon clicking a search function button. While I have successfully implemented the data flow, I am struggling to trigger the modal using the b ...

What is the best way to verify the font-family using JavaScript?

To verify if the user has installed the font family, we can run a JavaScript function with AngularJS. I am using a Typekit font and have only loaded this service for users who do not have this specific font. ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Setting a defined width and using block display will not solve the issue of the margin:auto not working

rough sketch of my desired design I am trying to center a label on the page. The parent container is set to a width of 100% and the label itself is displayed as a block element with margin set to auto. When I set the width of the label to a smaller value, ...

Getting request parameters within Model in Loopback can be done by accessing the `ctx`

common/models/event.json { "name": "Event", "mongodb": { "collection": "event" }, "base": "PersistedModel", "idInjection": true, "options": { "validateUpsert": true }, "http": { "path": "organizer/:organizer_id/events" }, "properties": {}, "va ...

Tips for indicating errors in fields that have not been "interacted with" when submitting

My Angular login uses a reactive form: public form = this.fb.group({ email: ['', [Validators.required, Validators.email]], name: ['', [Validators.required]], }); Upon clicking submit, the following actions are performed: ...

Save information in a session using html and javascript

I'm having trouble accessing a session variable in my javascript code. I attempted to retrieve it directly but ran into issues. As an alternative, I tried storing the value in a hidden HTML input element, but I am unsure of how to properly do that wit ...

Issue with passing PHP session variable during AJAX request processing

I've been working on a script that echoes different answers based on selected values. Right now, I'm just testing with one value but plan to expand later on. The PHP script is triggered through AJAX so the results display on the same page. Howev ...

What is the best way to implement nested iterations in Jade?

ul li a(href='') menu1 li a(href='') menu2 ul li a(href='') sub-menu2 li a(href='') menu3 ul li a(href=&apos ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

React Context - Ensure synchronized deletion of user posts across routes while maintaining pagination during fetching

INTRODUCTION I am striving to replicate the behavior commonly seen in social networks, where deleting a post by a user results in its automatic removal across all app routes. This functionality is reminiscent of how platforms like Instagram or TikTok oper ...

Is there a way to search for multiple items using just one search term?

On my app, there is a search bar that currently only looks up data for one specific attribute. For example, if I type in "Hammer," it only searches for Tool names. Now, I need to expand the search functionality to accommodate different types of strings. F ...