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

149
Views
Can I use event listener and document get Element By Id to change the source of an image?

JAVASCRIPT code is:

img1Click = document.querySelector('img#img1')

selected = document.querySelector('section.selected')
img = document.querySelector('img#imgcon')

img1Click.addEventListener('click', () =>{
    console.log('clicked')
   document.getElementById('imgcon').src('images/yellowcake.jpg')
})

This code is supposed to make change the src of a img of a div when another image is clicked.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You nearly had it, although src isn't a function!

You can set it by doing image.src = ... or image.setAttribute('src', '...')

Here is a simplified example:

const image = document.querySelector("img");

image.addEventListener("click", () => {
  image.setAttribute("src", "https://picsum.photos/id/2/200/200")
})
<img src="https://picsum.photos/id/1/200/200" alt="">

about 4 years ago · Juan Pablo Isaza Report

0

Yes, you can program

document.getElementById('id_of_element').src = 'image'

Where image is a base64 string or a file path in your directory (x.png).

about 4 years ago · Juan Pablo Isaza Report

0

const imgA = document.querySelector('#imgA');
const imgB = document.querySelector('#imgB');

imgA.addEventListener('click', () => imgB.src = imgA.src);
imgB.addEventListener('click', () => imgA.src = imgB.src);
<div>
  <img id='imgA' src="https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=64"/>
  
  <img id='imgB' src="https://lh3.googleusercontent.com/-ugd4YTD60WY/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclfd8tK4TmHmCGTFZSkqc8VSPTITA/s96-c/photo.jpg?sz=64"/>
</div>

about 4 years ago · Juan Pablo Isaza 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!