HTML
<div class="icon-menu">
<img src="../images/menu.png" id="navMenu" onclick="changeToCross()">
</div>
JS
function changeToCross() {
let menu = document.getElementById('navMenu');
let src = '../images/menu.png';
if (menu.src === src) {
menu.src = '../images/close.svg';
} else {
menu.src = src;
}
}
I want to change image source when it will be clicked but this code isn’t working. How can I fix it
>Solution :
The problem you are facing is that element.src is returning fully resolved URL, not the string that you’re setting. For example, if you’re on https://example.com/demo/page and use src="../images/menu.png" then menu.src would return https://example.com/demo/images/menu.png instead of the relative path.
In order to read the attribute value, you need to use element.getAttribute('src') which returns the raw value of the attribute.
So your code should be
if (menu.getAttribute('src') === src) {
To read up more on the topic, you can check what is the difference between properties and attributes in DOM.