Skip to content
Advertisement

Hello, I want that an icon on the page changes when I click on it (using JS) but It is not working

So the problem is that the JS is not working, can someone help me ?

function changeImage() {
    if (document.getElementById("threelines").src == "icons/3horlines.png") 
    {
        document.getElementById("threelines").src = "icons/close.png";
    }
    else
    {
        document.getElementById("threelines").src = "icons/3horlines.png";

    }
}
<button class="ButtonDefault" onclick="toggleNav()"><img  src="icons/3horlines.png"  alt="3horlines" height="30px" id="threelines" onclick="changeImage()">
        </button>

Advertisement

Answer

Not sure if this is what you are trying to do.

function changeImage() {
  const linesElement = document.getElementById("threelines");
  if (linesElement.getAttribute('src') == "icons/3horlines.png") {
    linesElement.src = "icons/close.png";
  } else {
    linesElement.src = "icons/3horlines.png";
  }
}
Advertisement