Skip to content

Instantly share code, notes, and snippets.

@bellrd
Created March 16, 2023 19:10
Show Gist options
  • Save bellrd/74e2bb29318a3a602122aa32a2e5ab1d to your computer and use it in GitHub Desktop.
Save bellrd/74e2bb29318a3a602122aa32a2e5ab1d to your computer and use it in GitHub Desktop.
Setting attribute 'onclick' on html element using javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- <button onclick="del('7');"> click to delete</button> -->
<div id="content"></div>
<script>
let state = ["cat", "dog", "elephant","ant"];
function echo(name) {
console.log(name + 7);
}
state.forEach((v, index)=> {
let b = document.createElement("button");
b.innerText = v.toUpperCase();
// b.setAttribute("onclick", `echo(${index})`);
b.onclick = function() {
echo(index);
} ;
document.getElementById("content").appendChild(b);
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment