Search code examples
javascriptgetelementbyidevent-listenersrciife

Why src in this.id.src undefined (in debugger) [inside an iife]


Why is the src in this.id.src undefined in debugger? I don't understand why this doesn't work. I've had this working before, but with a specific id (not this.id) Does anyone have any suggestions?

document.getElementById("a1").addEventListener("click", myFunction);

function myFunction (id) {
	console.log(this.id);  // works
	this.id.src="images/red.jpg";
}
<div>
<img id="a1" src="images/black.jpg">
</div>


Solution

  • There is no src property on the id property. You must used it directly this.src. And the parameter that is passed to the function is the event not the id:

    document.getElementById("a1").addEventListener("click", myFunction);
    
    function myFunction(e) {
      this.src = "http://via.placeholder.com/150x150";
    }
    <div>
      <img id="a1" src="http://via.placeholder.com/100x100">
    </div>