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

"Maximizing Data Interaction: The Integration of PHP and AngularJS

I have been developing an AngularJS App alongside a PHP RESTful API for the Backend. I am currently brainstorming about the most effective approach to harness the power of 2-Way Data Binding in AngularJS with my specific scenario. As an illustration, I ha ...

Can MUI 5 replicate the Emotions 'css' function through analog?

From what I've learned, MUI 5 utilizes Emotion for its styling framework. Emotion offers a convenient helper function called css, which generates a string - a class name that can be used as a value for the className property or any other relevant prop ...

Create a moving background gradient with styled-components

Currently, I am working on setting the background of the <Paper /> component using Material-UI version 1.0.0-beta.25 to display a gradient of colors. The colors are dynamically added by clicking the Add button and selecting one from the color picker. ...

What could be causing the routing to fail in this script?

Currently working on a small project to dive into AngularJS, and I'm facing some challenges with getting the routing to function properly. Despite following numerous tutorials, my code doesn't seem to be working as expected. If anyone could lend ...

jQuery event triggers upon completion of execution

A custom code has been integrated into my project using jQuery. Check out the code snippet below: <script> $("#startProgressTimer").click(function() { $("#progressTimer").progressTimer({ timeLimit: $("#restTime").val(), onFinish ...

The error message "TypeError: Unable to access the 'get' property of an undefined vue js object" appeared

Struggling to grasp the concept of vue.js, I am currently navigating my way through understanding how to fetch or call an API. Setting up my index.html and app.js, along with the required packages in the node_modules, has been relatively smooth. However, ...

Attempted everything... Clicking away but a div refuses to show up post-click, resulting in an error message

When attempting to click a button, I encountered an error stating that the element is not clickable at point (1333, 75) as another element would receive the click. This issue arose while using Google Chrome version 65. <li class="slds-dropdown-trigge ...

Guide to integrating jssor into an AngularJS application

Struggling to integrate jssor with angularjs, it seems to be failing because jssor is being initialized before angularjs, causing the ng-repeat elements to not resolve correctly. <div id="slider1_container"> <div u="slides"> <!-- Th ...

Show a single jQuery Validation error

I am struggling with displaying an error message at the top if validation fails, without using the errorPlacement option. Instead, I want to showcase the message in a Bootstrap alert box. Below is the HTML code snippet: <form method="POST" action="/ro ...

Did I incorrectly pass headers in SWR?

After taking a break from coding for some time, I'm back to help a friend with a website creation project. However, diving straight into the work, I've encountered an issue with SWR. Challenge The problem I'm facing is related to sending an ...

Managing browser back button functionality

I've been struggling to find a solution for handling the browser back button event. I would like to prompt the user with a "confirm box" if they click on the browser back button. If they choose 'ok', I need to allow the back button action, ...

Embarking on the journey of creating mobile web applications - where should you begin?

How can I begin learning to create mobile web apps? I have a keen interest in the design aspects, particularly the effects and animations that give them a native appearance. I suspect there are differences in CSS, HTML, and possibly JavaScript compared to ...

Utilizing pure JavaScript to dynamically fetch HTML and JavaScript content via AJAX, unfortunately, results in the JavaScript

I am trying to load an HTML file using AJAX and then execute a script. Here is the content of the HTML file I want to load: <div class="panel panel-body"> <h4>Personal Data</h4> <hr /> <span data-bind="editable: firs ...

What kind of interference occurs between the sibling components when a div with ng-if is present in Angular?

I've been troubleshooting for hours to figure out why the Angular elements in one div suddenly stopped working. After some investigation, I realized that a sibling div with an ng-if="someVar" was causing the issue. Currently, when someVar is true, the ...

Visual Composer in WordPress is not displaying as expected

I've attempted to uninstall and reinstall Visual Composer, but I'm unable to resolve the issue. I can't edit the front end because it's not displaying properly. I'm using the Ken theme. When checking the console, I encountered this ...

Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined Check out the code snippet below: <template> ... </template> <style lang="scss"> ... </style> <script> export default { ...

Display a snippet of each employee's biography along with a "Read More" button that will expand the content using Bootstrap, allowing users to learn more about each team

I have successfully developed a Google App Script that links to a Google Sheet serving as a database. The application iterates through each row, and I showcase each column as part of an employee bio page entry. ex. Picture | Name | Title | Phone | Email ...

Calculate the total width of LI elements and apply it to the parent UL or DIV

Is there a way to calculate the Total LI width and then set the width for the parent div? Here is an example of my code: <ul> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds&l ...

What is the method for eliminating the box shadow on a table?

Seeking assistance on removing the shadow effect from ng-tables upon hovering. Can someone guide me on how to achieve this? See screenshot here: http://prntscr.com/jcpl5g widget-body { background-color: #fbfbfb; -webkit-box-shadow: 1px 0 10px 1px rgba(0, ...

Div element positioned outside of another div element

I hate to bug you with more css issues, but I'm really struggling with this one. The problem I'm facing is that a sub div is overflowing the boundaries of its parent div. I tried using: display: inline-block;` but then the outer div goes haywir ...