Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly.

 document.getElementsByClassName(".try").forEach({
    if(element.classList.contains(".lol"))
{
        <img src=""/>;
    }
    else {<img src=""/>}
});

I know this code is incomplete, but what am I missing? I would greatly appreciate it if someone could provide me with instructions or documentation on how to achieve this.

<div class="try lol"></div>
<div class="try "> </div>
<div class="try lol"></div>

I need the function to iterate through every div with the class "try" and check if it also has the class "lol". If "lol" is present, I want the function to insert an image into the div. I plan to use a loop because there are many divs with the "try" class, each potentially requiring a different image based on the next div's class (e.g. showing image 1 for "lol", image 2 for "lol2").

Answer №1

To insert images on a webpage, you can utilize JavaScript in two ways:

const defaultImgSrc = 'https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg';
const lolImgSrc = 'https://images.freeimages.com/images/small-previews/1c9/maine-at-4-45-am-1370871.jpg'

document.querySelectorAll('.try').forEach(item => {
  const imgEl = document.createElement('img');
  imgEl.src = item.classList.contains('lol') ? lolImgSrc : defaultImgSrc
  item.append(imgEl);
});
<div class="try">
  <p>1</p>
</div>

<div class="try lol">
  <p>2</p>
</div>

<div class="try">
  <p>3</p>
</div>

<div class="try">
  <p>4</p>
</div>

<div class="try lol">
  <p>5</p>
</div>

Alternatively, you can include the default images directly in the HTML code and then dynamically change the src attribute for elements with the parent having the lol class using JavaScript:

document.querySelectorAll('.lol').forEach(item => {
  item.querySelector('img').src = 'https://images.freeimages.com/images/small-previews/1c9/maine-at-4-45-am-1370871.jpg';
});
<div class="try">
  <p>1</p>
  <img src="https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg">
</div>

<div class="try lol">
  <p>2</p>
  <img src="https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg">
</div>

<div class="try">
  <p>3</p>
  <img src="https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg">
</div>

<div class="try">
  <p>4</p>
  <img src="https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg">
</div>

<div class="try lol">
  <p>5</p>
  <img src="https://images.freeimages.com/images/small-previews/468/winter-wonderland-1383617.jpg">
</div>

Answer №2

If you want to understand the inner workings of Javascript, a good starting point is to explore how different methods like getElementsByClassName function within an HTMLCollection. While this method does not support forEach, you can access it by converting the collection into an array:

Array.from(document.getElementsByClassName(".try")).forEach(element => {
  your code here..
})

In addition, remember that rendering HTML directly within your JavaScript file is not possible. Instead, create new elements like so:

let img = document.createElement('img');
img.src = "...";
element.appendChild(img);

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

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

Issue with ThreeJS CSG when trying to intersect extruded geometries

element, I'm facing a challenge with extracting multiple views and intersecting them to form a final polygon. The issue arises when there are floating extra parts in the result that are unexpected. My goal is to find a solution to detect these extrane ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

Using Twig path to pass Ajax URL parameter

I'm facing an issue in my Twig view when passing parameters in the AJAX URL path. Since Twig is executed before JavaScript, it doesn't recognize the input value passed as a parameter. Is there a way to solve this without passing the param in data ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

Modifying Data in Another Component in VueJS

I have a classic Vue Component structured like the following: Vue.component('bar', { template: `<div class="bar"></div>`, data () { return { blocks: [ ] ...

Is there a way to utilize localStorage to retain a classlist toggle status for a light/dark mode theme switch on the browser?

I am currently working on a portfolio website that features a light/dark mode theme switch. The functionality of the switch is working properly, but it doesn't save the user's preference when they refresh the page or navigate to another section. ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...

Html content overlapping div rather than being stacked vertically

My goal is to arrange a group of divs inside another div in a vertical stack. However, I am facing an issue where the text from the last div is overlapping with the second div instead of following a proper vertical alignment where the text in the third div ...

"Enhance user experience with AJAX for selecting multiple checkboxes or performing mult

Hey there! So, I've got a question about handling multiple checkboxes with the same name in a form. Here's an example of what I'm working with: <input type="checkbox" name="myname[]" value="1" /> <input type="checkbox" name="myname ...

Tips for incorporating external AMD modules with Angular2 using WebPack

In my current project using Angular2, TypeScript, and WebPack, I am looking to incorporate the Esri ArcGIS JavaScript API. The API can be accessed from the following URL: By importing Map from 'esri/Map';, I aim to import the corresponding modul ...

Transfer the script from package.json to an npm package

In each of our plugins' root directories, there is a file named tools.js. This file contains a build function that assists in creating builds for the plugin. The package.json file references it like this: "scripts": { "build:node&qu ...

Retrieve an item from an array based on the unique ID value of the button that was clicked using

I am working with a phones array that is populated with JSON data: var phones = [ { "age": 0, "id": "motorola-xoom-with-wi-fi", "imageUrl": "img/phones/motorola-xoom-w ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Signing out in React js

Hey everyone! I'm facing an issue. I have to create a logout form on React js that redirects to loginindex.html from hello.ejs and clears some variables using server.js, but I'm not sure how to do it =( Can anyone offer some guidance? Thank you! ...

Is there a way to allow an HTML page rendered by node.js to communicate back to its corresponding node.js file?

I am currently in the process of developing a registry system using node.js and HTML. However, I have encountered an issue where my HTML page is rendered by node.js, but when trying to call it back to the node.js file, it appears that the JS file cannot be ...