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

128
Views
Image src won't change using JavaScript

I feel like I have this right, but for some reason, the addEventListener isn't functioning how I want it to. When I try to change the img.src below, it still only shows the 'images/expand.jpeg' img. I have confirmed that the path to the image is correct, as it does show the 'images/collapse.png' when I change the button's original src to 'images/collapse.png'.

document.querySelectorAll('.title').forEach(function(){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg"; 
    eachTitleDiv.append(button);
    button.addEventListener('click', function(){
        if (button.src === "images/expand.jpeg") {
            button.src = "images/collapse.png";
        } else if (button.src === "images/collapse.png") {
            button.src = "images/expand.jpeg";
        };
    });
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Relative src attribute computes to absolute URL in the DOM

  1. When you access the src attribute, it's the computed DOM value, and your relative link was computing to the absolute link. (https://yourwebsite.com/images/expand.jpeg === "images/expand.jpeg") returns false
  2. ALWAYS have an alt on your images, like in this case where they don't load, for visually impaired, SEO so many reasons!

Here is a working snippet where the alt is used to check state rather than the src:

document.querySelectorAll('.title').forEach(function(eachTitleDiv){
    let button = document.createElement('img');
    button.classList.add('smallbutton');
    button.src = "images/expand.jpeg";
    button.alt = "expand"
    eachTitleDiv.append(button);
    button.addEventListener('click', (e) => {
        if (button.alt === "expand") {
            button.src = "images/collapse.png";
            button.alt = "collapse"
        } else if (button.alt === "collapse") {
            button.src = "images/expand.jpeg";
            button.alt = "expand"
        };
    });
});
<h1 class="title">Title 1</h1>
<h2 class="title">Title 2</h2>
<p>Not a title</p>

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!