Skip to content
Advertisement

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.

JavaScript
JavaScript

Advertisement

Answer

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.

JavaScript
JavaScript

Hope that helps 🙂

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