Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Display different images on the same web page

I am trying to have each div display a different uploaded image but when I try uploading a picture with the second div it instead changes the first div's picture and nothing happens to the second div.

<div class="user-img">
    <img src="./images/image.jpg" alt="Avatar" id="photo">
    <input type="file" id="file" accept="image/*">
    <label for="file" id="uploadbtn"><i class="fas fa-camera"></i></label>
</div>
<div class="user-img">
    <img src="./images/image.jpg" alt="Avatar" id="photo">
    <input type="file" id="file" accept="image/*">
    <label for="file" id="uploadbtn"><i class="fas fa-camera"></i></label>
</div>
<script>
    const img = document.querySelector('#photo');
    const file = document.querySelector('#file');

    file.addEventListener('change', function(){
        const chosenFile = this.files[0];
        if(chosenFile){
            const reader = new FileReader();
            reader.addEventListener('load', function(){
            img.setAttribute('src',reader.result);});
            reader.readAsDataURL(chosenFile);
        }
});
</script>
almost 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can't have two elements with the same ID of file and Photo. ID's Should be unique. In this case you should utilize classes instead.

Then use document.getElementsByClassName() to receive an array of elements which you can iterate through and add the event listener to the file elements.

almost 4 years ago · Santiago Trujillo Report

0

Change your <img> elements to use class names, rather than id's. Ex:

<img src="./images/image.jpg" alt="Avatar" class="photo">

Next grab your images using a document.getElementsByClassName() call like the following

const imgs = document.getElementsByClassName('photo');

Then you can loop through the imgs array and set the src attribute, like so

imgs.forEach((img) => {
  img.setAttribute('src', reader.result);
});
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!