Tips for updating a portion of your code using new variables in JavaScript

I'm currently working on implementing a commenting feature for my website. The goal is to display new comments above the existing comment section when users submit their feedback. However, I'm facing challenges in dynamically updating the HTML with the new comments using JavaScript. My aim is to maintain consistency in the formatting of the new comment compared to the initial comments displayed. How can I achieve this? Apologies if my explanation is not clear enough :/

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();
    console.log('comment button pressed');

    var userComment=document.getElementById("comment-box").value;
    console.log(userComment)

    var text= document.createTextNode(userComment);
    console.log(text)

    var newComment = document.getElementById("new-comment");
    console.log(newComment)

    newComment.appendChild(userComment)
    


})
  .comment-box,
  .post-comment .list{
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 2px 2px black;
  }

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;  
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}




#comment-box{
  border:none;
  border-radius: 5px;
}


.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}
<div class="post-comment">
          <div class="list">
            <div class="user">
              <div class="user-image"><img src="./images/ok.webp"></div>
              <div class="user-name">
                <div class="name">TOM</div>
                <div class="day">100 days ago</div>
              </div>
            </div>
            <div class="comment">LOREM IPSUN DABUN VUB</div>
          </div>
          <div id="new-comment">  </div>

          <div class="comment-box">
            <div class="user">
              <div class="user-image"><img src="./images/OK.webp"></div>
              <form>
              <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
              <button id="post">Comment</button>
            </form>
          </div>

        </div>
      </div>
     </div>

Answer №1

You're so close! The key is to pass a node when using the appendChild() method.

Start by creating a div node,

// create an element node
// var text = document.createTextNode(userComment);
var text = document.createElement('div');
text.innerText = userComment;

Then, add it to the new comment section,

// note: you need to pass a node to appendChild() method
// newComment.appendChild(userComment);
newComment.appendChild(text);

Hope this explanation helps!

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();
    console.log('coment button pressed');

    var userComment = document.getElementById("comment-box").value;
    console.log(userComment)

    // create an element node
    // var text = document.createTextNode(userComment);
    var text = document.createElement('div');
    text.innerText = userComment;
    console.log(text)

    var newComment = document.getElementById("new-comment");
    console.log(newComment)

    // note: you need to pass a node to appendChild() method
    // newComment.appendChild(userComment);
    newComment.appendChild(text);
})
.comment-box,
.post-comment .list{
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 2px black;
}

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;  
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}




#comment-box{
  border:none;
  border-radius: 5px;
}


.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}
<div class="post-comment">
    <div class="list">
      <div class="user">
        <div class="user-image"><img src="./images/ok.webp"></div>
        <div class="user-name">
          <div class="name">TOM</div>
          <div class="day">100 days ago</div>
        </div>
      </div>
      <div class="comment">LOREM IPSUN DABUN VUB</div>
    </div>
    
    <div id="new-comment"></div>

    <div class="comment-box">
      <div class="user">
        <div class="user-image"><img src="./images/OK.webp"></div>
        <form>
        <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
        <button id="post">Comment</button>
      </form>
    </div>

  </div>
</div>

Answer №2

You need to make a change in the code snippet from

newComment.appendChild(userComment)
to newComment.appendChild(text);. Furthermore, I have made some additional modifications such as clearing the text area after submitting a comment and displaying each comment in a separate paragraph to avoid them appearing on the same line:

var post= document.getElementById("post");
post.addEventListener("click",function(e){
    e.preventDefault();

    var userComment=document.getElementById("comment-box").value;
    
    var text= document.createElement('p');;
    text.innerHTML = userComment;

    var newComment = document.getElementById("new-comment");

    newComment.appendChild(text);
    document.getElementById("comment-box").value = "";
   
})
  .comment-box,
  .post-comment .list{
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 2px 2px black;
  }

.comment-section{
  width: 100%;
  height: auto;
  margin: 0 auto;
}

.post-comment .list{
  width: 100%;
  margin-bottom: 12px;
}

.post-comment .list .user{
  display: flex;
  padding: 8px;
  overflow: hidden;
}

.post-comment .list .user img{
  height: 38px;
  width: 38px;
  margin-right: 10px;
  border-radius: 50%;  
}

.comment-section .name{
  text-transform: uppercase;
}

.post-comment .list .day{
  font-size: 12px;
}

.post-comment{
  padding: 0 0 15px 58px
}




#comment-box{
  border:none;
  border-radius: 5px;
}


.comment-box .user{
  display: flex;
  width: min-content;
}

.comment-box .image img{
  width:24px;
  height: 24px;
  margin-right: 10px;
  border-radius: 50%;
}

.comment-box textarea{
  height: 50px;
  width: 1 ;
  background-color: white;
  margin: 10px 0;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 0 1px black;
}
<div class="post-comment">
          <div class="list">
            <div class="user">
              <div class="user-image"><img src="./images/ok.webp"></div>
              <div class="user-name">
                <div class="name">TOM</div>
                <div class="day">100 days ago</div>
              </div>
            </div>
            <div class="comment">LOREM IPSUN DABUN VUB</div>
          </div>
          <div id="new-comment"></div>

          <div class="comment-box">
            <div class="user">
              <div class="user-image"><img src="./images/OK.webp"></div>
              <form>
              <textarea name="comment" placeholder="YOUR MESSAGE" id="comment-box"></textarea>
              <button id="post">Comment</button>
            </form>
          </div>

        </div>
      </div>
     </div>

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

Is my HTML <h1> text not updating properly? I'm wondering if I linked app.js correctly

I'm currently learning the basics on a new machine and facing an issue where I am unable to modify the text within the header. It appears that the app.js file might not be properly connected to my index.html file. Within the app.js file, I have the f ...

Trouble viewing Three.js content in Index.html

My current project involves building a website using three.js with typescript. However, I am facing an issue where only the header from my index.html file is displayed when I try to load the website onto a local server. The main problem arises when I atte ...

Having trouble implementing server-side rendering with Styled-Components in Next JS

I attempted to resolve my issue by reviewing the code and debugging, but unfortunately, I couldn't identify the root cause. Therefore, I have posted a question and included _document.js, _app.js, and babel contents for reference. Additionally, I disa ...

Merge two scripts together

I'm facing an issue with my frontend due to having two separate scripts in my Vue.js component class. How can I merge them into one cohesive script? If the problem stems from elsewhere, what could it be? <script> import GETUSER from "@/graphql/ ...

Deactivate certain input elements when a specific radio option is chosen

Just starting out with JQuery here. I'm working on a search form that has 16 fields, most of which are textboxes and the rest are dropdowns. Underneath these fields, I have 3 radio buttons. When the first one is selected, certain fields in the form s ...

Position an image at the center within a footer widget

I am attempting to position an image at the center of a footer widget. I have gone through various solutions recommended here, but I am unsure if I am implementing the code correctly. Here is my CSS: #footer img.center { display: block; margin-le ...

The term "landscape" to address the issue of adjusting the Android app screen to display in landscape orientation is not being acknowledged

I am working on an Android app using HTML5 and Cordova. I've included the following code in the manifest.json file as a reference. However, I'm facing an issue where the app screen does not stay fixed horizontally. It only turns sideways when th ...

What occurs to the node request stream before it is utilized?

Currently, I am developing a node application that involves piping the body of a post request into a writable stream for saving data to disk. While working on this project, it has come to my attention that I lack knowledge about what happens to the request ...

Error on the main thread in NativeScript Angular for Android has not been caught

As a beginner in the field of mobile development, I am currently exploring NativeScript and encountering an error in my Android application. https://i.stack.imgur.com/BxLqb.png You can view my package.json here ...

Individual files dedicated to each controller in Angular.js are a common practice in development

In my project, I am looking to create an Angular module with a main controller, as well as additional controllers that are stored in separate files. Main module: var app = angular.module("main", []); app.controller("mainCtrl", function ($scope) { $scop ...

Creating a clickable map for a PNG image: Step-by-step tutorial

My goal is to create a interactive map similar to this one. Click here for the image ...

Getting around popup blockers on safari

Here is the HTML code I am working with: <a href = "#" class="fb">Facebook</a> I am using an onclick event handler that triggers window.open when the link above is clicked. This works fine in Chrome, but it does not work in Safari. How can I ...

"Is it possible to access variables declared in the main app.js file from separate route files in Node.js Express 2.5.5 and if so

Recently, I've started using the latest version of Express (2.5.5) which now automatically creates a ./routes directory in addition to ./views and ./public In the routes directory, there is an index.js file that includes: /* * GET home page. */ e ...

Guide to putting a new track at the start of a jPlayer playlist

I am currently working on a website that utilizes the jPlayer playlist feature. I am facing an issue, as I need to implement a function that adds a song to the beginning of the playlist, but the existing add function only appends songs to the end of the pl ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...

Is it necessary to bring in CSS for the following page?

Should CSS be imported and used across multiple pages in a web application? Is the page structure outlined below considered acceptable, or is there a standard practice to follow? /pages /home index.js index.module.css /cart ...

JavaScript: void(0), Internet Explorer 6, and SWFAddress are all important components

Hello there, We are on the verge of launching a secure website (regrettably, we cannot provide the URL) and have come across a rather obscure bug in IE6 that I am hoping someone may have experienced or could shed some light on. This issue only arises when ...

Issue with three.js memory leak due to malfunctioning .dispose() method or incorrect usage

Greetings! I'm currently facing a memory handling issue. Despite researching various forums, I am still unable to identify the problem in my code. My project involves combining d3.js with three.js to create a visualization of nodes resembling planet ...

Waiting for all promises to resolve: A step-by-step guide

I need to make two different API calls and perform calculations based on the results of both. To wait for both promises to resolve, I am using Promise.all(). const getHashTagList = async () => { loader.start(); try { await getAllHashTag ...

Split-screen homepage design (CSS)

I am trying to design the homepage for my site using only html/css add-ons and without altering any other rule. So far, I have managed to create the blocks themselves but I'm stuck on how to position images behind the buttons, center everything verti ...