I tried to create an html file that adds a string each time a button is pressed with the following code:
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
</head>
<body>
<form id="form">
<button type="button" id="a">add</button>
</form>
<script>
const txt = "hello world ";
const el = document.createTextNode(txt);
document.body.appendChild(el);
const f1 = document.querySelector("#a");
f1.addEventListener("click", () => {
document.body.appendChild(el);
console.log("hi");
});
</script>
</body>
</html>
However, when I run this code, only document.body.appendChild(el)
doesn’t work. Both console.log
in the function and appendChild
outside the function work well. Any ideas? Thanks