Utilizing document.getElementById dynamically to access multiple elements with the same ID

const imageOne = document.getElementById('imageOne');
const modalImage = document.getElementById("img01");
let altText = document.getElementById("caption");
imageOne.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    modalImg.alt = this.alt;
    captionText.innerHTML = this.alt;
}
#imageOne {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}
<img id="imageOne" src="imageone.jpg" alt="Image one" >

<br>
<br>
<img id="imageTwo" src="imagetwo.jpg" alt="Image two" >

The above code snippet is from a CSS3 tutorial on modal images. It's crucial to note that having multiple tags with the same ID is not recommended, and the solution involves using dynamic IDs in JavaScript.

const imageOne = document.getElementById('imageOne');

I'm trying to figure out how to dynamically change getElementById so I can utilize more than one image with different sources. Research suggests that using a Tag selector or Class selector isn't the appropriate approach.

If anyone has any resources or documentation to help me improve my understanding, I would greatly appreciate it.


I've made good progress with the CSS styling, and everything looks fantastic. My next goal is to display text when the modal pops up utilizing existing alt attributes. Here's the current JavaScript line I have:

let altText = document.getElementById("caption");

Below is the HTML structure I plan on using to showcase unique alt text for each image inside the modal popup:

I've attempted to implement this but it doesn't seem to be working. Could the issue lie in my CSS formatting?

Answer №1

To efficiently process a group of elements that require the same treatment, it is recommended to utilize the class attribute for targeting.

Instead of singularly targeting an element with: document.getElementById, you can obtain a collection of elements known as a NodeList by using document.getElementsByClassName or document.querySelectorAll.

Subsequently, iterate through these elements and apply the previously written code accordingly.

Below is a practical example:

var imgs = document.getElementsByClassName('myImg');

for (var i = 0; i < imgs.length; i += 1) {
  var img = imgs[i];

  img.onclick = function() {
    // implement your onclick functionality here
  };
};

Remember to update the HTML markup as follows:

<img class="myImg" src="imageone.jpg" alt="Image one" >

Answer №2

Thank you for checking this out!

let images = document.querySelectorAll('.gallery-img');

if (images) {

  for (let i = 0; i < images.length; i++) {
    images[i].addEventListener('click', displayModal, false);
  }

}

function displayModal() {
  let modalBox = document.querySelector('.modal');
  if (modalBox) {
    let imageElement = modalBox.querySelector('img');
    let closeBtn = modalBox.querySelector('.close');
    modalBox.classList.add('open');
    imageElement.src = this.src;

    if (closeBtn) {
      closeBtn.addEventListener('click', closeTheModal, false);
    }
  }
}

function closeTheModal() {
  this.parentNode.classList.remove('open');
}
img {
  width: 200px;
  cursor: pointer;
  border: 2px solid transparent;
}
img:hover {
  border: 2px solid #191919;
}
.modal {
  display: none;
  width: auto;
  height: auto;
  background: #ccc;
  border-radius: 4px;
  padding: 6px;
}
.modal.open {
  display: inline-block;
}
.modal .close {
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  display: block;
  text-align: right;
}
<img class='gallery-img' src="http://wallpaperbeta.com/wallpaper/small_fish_by_name_beta_minimalism_hd-wallpaper-296364.jpg" alt="">

<img class='gallery-img' src="https://wallpaperscraft.com/image/flowers_small_flower_surface_rose_43393_2048x1152.jpg" alt="">

<div class="modal">
  <span class="close">&times;</span>
  <img src="" alt="">
</div>

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

Guide: Looping through a typed Viewbag array - best practices

I have passed a List<AdminUsers> through the Viewbag to a view. This list is then assigned to a JavaScript variable and looped through. However, when debugging on the view, I noticed that the for loop is not being executed, even though I set a break ...

What is the best way to manage the maximum number of concurrent AJAX requests?

I am currently working on an autocomplete search bar feature. <input type="text" class="form-control" id="text" > <script> $("input").keyup(function(){ let key = $("input").val(); ...

Refreshing the webpage with new data using jQuery after an AJAX request is

I'm experiencing a problem where the DOM is not updating until after the completion of the $.each loop. On my website, I have several div elements that are supposed to turn orange as they are being looped over. However, once the data is sent to the s ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

The action creator is not being triggered when the onClick event is called on a material-ui button

Upon calling the action creator for an onClick event on a material ui RaisedButton, I encountered the following error Failed prop type: The onClick prop of type object was provided to RaisedButton, but it was expected to be of type function. This is my c ...

What is the best way to preserve code in a blog post without any alterations to the code itself?

@"//div[@id='transcriptText']/div[@class='notranslate']/p/a/@href"]; @"//div[@id='videoPlayerSWF']/noscript/div/p/a/@href"]; @"//div[@id='transcriptText']/div/p/a/text()"]; @"//div[@id='transcriptT ...

Console.log() will not display any JSON duplicates

My JSON data structure is pretty flat and can have duplicate attributes. I built a logic to remove the duplicates but when testing it out, something strange happened. The logic was always counting the attributes once, resulting in no duplicates. To test th ...

"JSON.parse encounters issues when attempting to parse correctly formatted JSON data

During the development of my application, I encountered an issue when trying to send a large JSON file consisting of about 7 million characters (6.6 MB of data). Although the JSON is correctly received as a string, I faced an error when attempting to parse ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Update the contents of a webpage using AJAX

Can anyone help me with loading likes into a div using AJAX every second? I want the page's URL to be likes.php?p=0 on page load, likes.php?p=1 after 1 second, likes.php?p=2 after 2 seconds, and so on. This is my code snippet: var loadLikes = func ...

How can you utilize jQuery to eliminate specific select field values from the DOM prior to submission?

I am currently working on a Squarespace form that utilizes jQuery to show/hide specific fields in order to create a customized form using the show(); and hide(); functions. $(".option2 select").hide(); The issue I am facing is that simply hiding the fiel ...

What's preventing me from utilizing Leaflet Map on Next.js despite attempting Dynamic Import?

When using Leaflet, it requires the global window object which is not available on SSR (Server-Side Rendering) and can cause an error stating "window is not defined". I have tried extensively to find a solution, and the only method I found was to use dyna ...

I would like to know how to create a dropdown menu that shows the country name, flag, and code based on the

I have successfully generated the telephone input field. One requirement is to display the Country flag along with the country name as soon as the dropdown is selected. Another requirement is that once the country is selected, it should display the countr ...

What could be causing my HTML form elements to shift position when I click on them in Internet Explorer 8?

I'm facing an issue with my HTML form that has multiple input fields (text and select types) arranged in pairs on each row. Surprisingly, everything works fine in all browsers, including IE7. However, when it comes to IE8, I encounter a peculiar probl ...

Struggling with configuring AngularJS?

I've been working on a simple setup, but I can't figure out why AngularJS isn't displaying the content within the curly brackets. It's got me completely baffled. If you'd like to check it out, here's the link to the plunker: ...

Various issues arising from a single input in Foundation Abide with AngularJS

Trying to set up a form using Foundation has proven challenging, especially when it comes to implementing more advanced error checking. If we take the example of an input field like this: <input pattern="username" required type="text" placeholder="user ...

Is it possible to stack images on top of each other on a webpage?

I'm looking to create a dress-up game website where users can click on different accessories to layer them on top of each other. It's a bit tricky to explain, but I've found some examples that demonstrate what I have in mind: This site is ...

Adding React components dynamically through code

My journey with React is just beginning, and I am faced with a challenge of adding new components to an existing setup. However, I'm unsure of the process. Here is my current scenario: I have a list of Seances along with a button to add more: Seanc ...

Encrypt JavaScript for a jade layout

I need to find a way to successfully pass a .js file to a jade template in order for it to display correctly within an ACE editor. However, I am encountering errors when attempting to render certain files that may contain regex and escaped characters. How ...