I've been working on a simple comment script that allows users to input their name and message, click submit, and have their comment displayed on the page like YouTube. My plan was to use a prebuilt HTML div and clone it for each new comment, adjusting the text accordingly. However, I'm running into an issue where no element is cloned into the container when I press submit. This has become a major roadblock in my project.
UPDATE: After making some adjustments to the code, I now encountering a new error message (
Cannot read property 'appendChild' of null
)
window.onload = () => {
const template = document.comment;
const form = document.forms.comment;
const container = document.querySelector('.container')
form.submit2.addEventListener('click', () => {
const name = form.name;
const text = form.text;
const newNode = template.cloneNode(true);
newNode.classList.remove('hidden')
container.appendChild(newNode)
})
}
.hidden {
display: none;
}
.comment-form input {
display: block;
padding: 2px;
}
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" href = 'style.css'>
</head>
<body>
<form name = "comment" class = "comm">
<input type = "text" maxlength = 20 name = 'name' placeholder = 'name'>
<textarea name = "text" placeholder = 'comment'></textarea>
<input type = "button" value = "submit" name = "submit2">
</form>
<div name = "comment" class = 'hidden'>
<h1>Demo</h1>
<p>Paragraph</p>
</div>
<div class = "container"></div>
<script src = "script.js"></script>
</body>
</html>