add onclick property to appended element code example

Example: add onclick property to appended element

<!DOCTYPE>
<html lang="en-GB">
<head>
<meta charset="utf8">
</head>

<body>
<div id="span-holder"></div>

<script>
var elem = document.createElement('span');
elem.className = "newSpan";
elem.innerHTML = "My shiny new span element";
elem.onclick = function(){ alert('Hi!'); };

var spanHolder = document.getElementById('span-holder');

spanHolder.appendChild(elem);
</script>

</body>
</html>

Tags:

Misc Example