I have created 4 buttons and every button with its own id and I have a function that displays the given element id. so I want to apply it on all this 4 buttons. what did I do wrong?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='b1'>Click</button>
<button id='b2'>Click</button>
<button id='b3'>Click</button>
<button id='b4'>Click</button>
<script type="text/javascript">
function show_id(element){
alert(element.id)
}
for(i=0; i!=document.getElementsByTagName('button');i++){
target = document.getElementsByTagName('button')[i]
target.onclick = show_id(target)
}
</script>
</body>
</html>
i!=document.getElementsByTagName('button').length. As it stands, you're comparing a number to an HTMLCollection, potentially creating an infinite loop, only stopped by the error it creates inside the loop.