Why Isn't the Element Replicating?

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>

Answer №1

window.addEventListener('load', e => {
  const template = document.querySelector('.comment-template');
  const form = document.querySelector('.comment-form');
  const container = document.querySelector('.container');

  form.querySelector('.submit-button').addEventListener('click', e => {
    const newNode = template.cloneNode(true);

    newNode.querySelector('.name').innerText =
        form.querySelector('.name').value;
    newNode.querySelector('.comment').innerText =
        form.querySelector('.comment').value;

    newNode.classList.remove('hidden');
    container.appendChild(newNode);
  });
});
.hidden {
  display: none;
}

.comment-form input {
  display: block;
  padding: 2px;
}
<form class="comment-form">
  <input type="text" maxlength="20" placeholder="name" class="name">
  <textarea name="text" placeholder="comment" class="comment"></textarea>
  <input type="button" value="submit" class="submit-button">
</form>

<div class="comment-template hidden">
  <h1 class="name"></h1>
  <p class="comment"></p>
</div>

<div class="container"></div>

Modifications were made to the script, utilizing querySelector instead of direct name access. The issue with the container being retrieved as an array-like object was resolved by selecting only one element. Additionally, logic was added to insert the name and comment text into the cloned node.

Answer №2

window.onload = () => {
  let template = document.answer;
  // There are two elements with the same name 'comment'. It is currently referring to the form instead of the intended div.
  console.log("Current template", template);
  
  // To correct this, select the element by its class name instead
  template = document.getElementsByClassName('hidden')[0];
  console.log("Adjusted template", template);
  
  const form = document.forms.comment;
  console.log("Form element", form);
  
  // getElementsByClassName returns an array-like object even if there's only one matched element. Specify [0] to target a single element.
  const container = document.getElementsByClassName('container')[0];
  console.log("Container element", container);
  
  // With the change in naming from submit to submit2 for the button, attach the click event accordingly
  console.log("Submit button", form.submit2);
  
  form.submit2.addEventListener('click', () => {
    let name = form.submit2.name;
    console.log("Name", name);
    
    // The 'name' element is not a child of the submit button but a separate sibling element. Retrieve its value using the correct reference.
    name = form.name.value;
    console.log("Corrected name", name);
    
    let text = form.submit2.text;
    console.log("Text content", text);
    
    // Similar issue exists with the text input field
    text = form.text.value;
    console.log("Updated text content", text);
    
    const newNode = template.cloneNode(true);
    console.log("New cloned node", newNode.outerHTML);
    
    // Currently, the cloned node does not contain the name or text content. These need to be added before appending it to the DOM.
    newNode.getElementsByTagName('h1')[0].innerText = name;
    newNode.getElementsByTagName('p')[0].innerText = text;
    
    console.log("Final modified node", newNode.outerHTML);
    
    newNode.classList.remove('hidden');
    container.appendChild(newNode);
  })
}
.hidden {
  display: none;
}

.comm 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>

Presenting an alternative solution that walks through the original code, highlighting the issues and demonstrating their solutions while staying true to the initial approach.

Answer №3

The issue arose from my HTML elements containing unnecessary whitespace. It is important to avoid adding spaces around the = sign within HTML markup. No errors were found in the script implementation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use scrollIntoView() to display an additional item at the top or bottom of the visible area

When implementing scrollIntoView() with navigation buttons (up and down), I aim to display two items at a time to signal to the user that there are more items to navigate. However, the first and last items should retain their default behavior so the user u ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

Styling text of various sizes to appear together in a div container

I'm having trouble getting my text to align in a single line. I've tried using vertical-align: middle and vertical-align: bottom... Can someone please assist me? http://jsfiddle.net/2wDEw/ Here is a simple example of what I have: ...

The array functions properly when handwritten, but fails to work when loaded from a text file

I have been developing a password recommendation script that aims to notify users when they are using a commonly used password. In order to achieve this, I decided to load the list of common passwords from an external text file. However, it seems that the ...

The MUI snackbar element lingers in the DOM even after it has been closed

Having created a global modal with the intention of only utilizing it when necessary, I've encountered an issue where the snackbar div persists in the DOM. This persistence is causing certain elements to become blocked as they appear beneath this div. ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

Tips for choosing multiple values from a dropdown menu in Bootstrap CSS version 3

I'm looking to implement a way to select multiple values from a dropdown menu without using the CTRL key. Currently, I am utilizing Bootstrap CSS for styling. Here is the code for my dropdown: <select multiple class="dropdown-menu"> ...

Next.js: Dealing with special characters in YouTube video API snippet titles

Trying to find the perfect video snippet title without any special characters. Accessing the API: https://www.googleapis.com/youtube/v3/search, along with specifying snippet. The current output for snippet.title is as follows: I&#39;M GONNA CARRY ...

What sets apart the "+" and "~" selectors in CSS?

I've tried using both of these selectors, but I'm having trouble distinguishing between them. It appears that they are functioning in the same way. There must be a difference that I'm overlooking. ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Utilizing Angular's globally accessible variables

As we make the switch to Angular.js for our webapp, we are faced with the challenge of storing global data. In the past, we used a global object called app to store various functions and variables that needed to be accessed across different parts of the ap ...

Resolving issues with JavaScript caused by Polymer updates

I am a novice when it comes to working with Polymer. From what I have gathered, there seems to be compatibility issues with Mozilla and Safari. After researching on StackOverflow, I found that adding addEventListener('WebComponentsReady', funct ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

Preserve the iframe src value in the dropdown menu even after the page is refreshed

I am trying to figure out how to prevent the iframe src from changing when I refresh the page, unless the user manually changes it using the dropdown menu with JavaScript. Can someone help me with this? <div class="row"> <div class="span9"> ...

The variable 'X' in Node.js is not been declared

I've been struggling with this problem, trying to fetch my most recent tweets as an array using the npm module https://github.com/noffle/latest-tweets. However, no matter how I approach it, I always encounter errors such as 'posts is not defined& ...

CSS in flexbox nested with no overflow utilized

I have created a basic "table" layout using flexbox. I want to implement horizontal scrolling for a specific part of the table by using overflow-x property. When you look at the provided code snippet, you'll notice that the CSS styles are only visib ...

The initial number is inserted within the text box upon entering the final number

Whenever I enter the final digit, the text-box swallows up the initial number (it vanishes), resulting in an additional space. https://i.stack.imgur.com/Vfm8s.png https://i.stack.imgur.com/od4bQ.png Upon clicking outside of the text-box, the formatting ...

Tips for creating an array within an AngularJS Service and effectively sharing it across two controllers

I have two controllers, FirstController and SecondController, along with a service defined as follows: app.factory('Data', function(){ return []; }); In both controllers, I am utilizing the service in this manner: app.controller("FirstCont ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...