Example
HTML
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement -->
<!DOCTYPE html>
<html>
<head>
<title>||Working with elements||</title>
</head>
<body>
<div id="div1">The text above has been created dynamically.</div>
</body>
</html>
JavaScript
document.body.onload = addElement;
function addElement () {
var myImage = new Image(400, 100);
myImage.src = 'https://www.google.com/logos/doodles/2017/holidays-2017-day-2-5240850203279360-s.png';
myImage.id = "myImageId";
myImage.onclick = myVerySpecialFunction();
var tmp = "myVerySpecialFunctionAnswer()";
document.body.appendChild(myImage);
document.getElementById("myImageId").setAttribute("onclick", tmp);
}
function myVerySpecialFunction() {
alert("Knock-knock!");
}
function myVerySpecialFunctionAnswer() {
alert("Who is there!?");
}