Skip to content

How to toggle the “src” attribute of an image without using an if-statement?

the problem is I want to change the src of img tag by using the button which executes if, else function. but I think my code is unprofessional and there is a better way to do the same job.

let smile = true  
let test = () => {
   if (smile == true) {
     document.getElementById("image").src = "";
      smile = false
 else {
     document.getElementById("image").src = "";
     smile = true
 <img id="image" src="" width="160" height="120">
 <button type="button" onclick="test()">over here </button>



Here is another solution, wich is just 5 lines of JS. It uses if-else oneliners, to wich a detailed guide can be found here.

I also used the HTML data-attribute instead of a variable: data-smile="false"

I removed the id of the Element because you can just select it via the data-attribute.

let img = document.querySelector('[data-smile]');
img.onclick = () => { = == "true" ? "false" : "true";
    img.src = == "true" ? "" : "";
    <img src="" data-smile="false">

Hope that helps 🙂

User contributions licensed under: CC BY-SA
3 People found this is helpful