Tips for utilizing templates while maintaining your unique style

I created a div-block with the id "screen", an input field for text with the id "message_text", and a CSS template for message design.

Here is the HTML code for the template:

<template class="template_message" id="template_message">
      <div class="message">
            <p></p>
      </div>
</template>

And here is the JavaScript code:

document.addEventListener("DOMContentLoaded", ()=> {
    let button = document.getElementById("send_button");
    let template = document.getElementById("template_message");
    let screen = document.getElementById("screen");
    let message_text = document.getElementById("message_text");

    button.addEventListener("click", () => {

        let template_clone = template.content.cloneNode(true);

        template_clone.textContent = message_text.value;

        screen.appendChild(template_clone);

    })
})

My goal is to display the value of the "message_text" input field, but all I get is plain text without any CSS styling.

Answer №1

The problem you're encountering is that using .textContent will set the text content of the entire template, causing the HTML structure to change from

  <div class="message">
    <p></p>
  </div>

to just

message_text

Instead, you should target the .message > p element specifically and update its textContent like this:

template_clone.querySelector(".message > p").textContent = message_text.value;

which would result in the following HTML structure:

  <div class="message">
      <p>message_text</p>
  </div>

Here's an example snippet demonstrating both approaches:

let output1 = document.getElementById("output1");
let output2 = document.getElementById("output2");
let template = document.getElementById("template_message");

let clone1 = template.content.cloneNode(true);
// Replace entire template content
clone1.textContent = "New Message 1";
output1.appendChild(clone1, true);

let clone2 = template.content.cloneNode(true);
// Set just the message content
clone2.querySelector(".message > p").textContent = "New Message 2";
output2.appendChild(clone2);
.message { border:1px solid rebeccapurple; }
p { padding:0 0 0 3em; }
<template class="template_message" id="template_message">
      <div class="message">
            <p></p>
      </div>
</template>

<hr/>
<div id="output1"></div>
<hr/>
<div id="output2"></div>
<hr/>

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

Can someone explain this unfamiliar JavaScript array notation?

I've been struggling to find an answer on Google and Stack Overflow for the purpose of this JavaScript code snippet: obj['e'+type+fn]( window.event ); My interpretation is that it resembles accessing a specific array element with an argume ...

Remove the dotted border on a button using CSS

I seem to be having an issue with a button as displayed in this picture: Does anyone know how to remove the dotted white border that appears on the button when it is focused? If you need to refer to the online source and CSS + HTML codes, they can be fou ...

The required field validator's text property may stop displaying, but the error message will still show up in the validation summary

I am encountering an issue with a RequiredFieldValidator's text property. In my ASP web form, I have a Panel where I create a table with a textbox and a RequiredFieldValidator during the overridden OnPreInit event. This table is then stored in a sessi ...

Having trouble setting up react-i18n with hooks and encountering a TypeError: Cannot read property '0' of undefined?

Encountering an error while setting up the react-i18n with hooks: TypeError: Cannot read property '0' of undefined Here's the content of i18n.js: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next/h ...

Using CSS to responsively align the logo in the header with the name positioned on both sides

I'm struggling to align my logo in the center of my header. I want it to appear like this when displayed correctly: "Name" Logo "Surname". The logo should be centered, with the "name" on its left and the "surname" on its right. (Please refer to the im ...

Menu in Bootstrap 5 experiencing a jittery effect when hovered over

I am facing an issue with shaking when hovering over the link.nav where I have added a border-bottom to display on hover. <section id="main_header"> <div class="container-fluid mainbar-bg py-1"> <div class="conta ...

Error: Unable to modify the background color of this object as it is read-only

Currently, I am working with React in order to create a component that displays a different background based on its property. However, the challenge I am facing is how to modify the property without causing the React frame to crash. const inactiveStyle = { ...

Updating textures in Three.js

Is there a way to access and modify the data in an exported JSON file using JavaScript? For instance, if I have a material with specific properties like mapDiffuse value that I want to change, how can I achieve this through a JavaScript function? "materia ...

Engaging in Communication with Two Unique User IPs

Is there any way to facilitate communication between two users on a site? For example, if user1 clicks on user2's name (along with their IP address) and sends a message. I know that using a database and AJAX can save messages and send them to user2, b ...

Updating React state for no apparent reason

My issue is quite straightforward. In my application, I have a user list stored in the state which is populated by a database call. Additionally, there is a selected user that gets filled when an element in the user list is clicked. Whenever a userlist e ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...

Tips for dynamically adjusting price values in Magento

As someone new to Magento, I am looking to update the price value on a product's detail page dynamically using Ajax. Additionally, I would like this updated price to reflect in the cart page as well. To see an example of what I'm trying to achie ...

Troubleshooting: Issues with locating CSS and JS files (404 error) while utilizing URL parameters within Django platform

I've designed a dashboard page that showcases various graphs. The page automatically updates the graph data every hour. You can access the page at the following URL: http://localhost/dashboard I'd like to give users the option to specify the ...

While attempting to add a member to a role, I encounter the following error: ReferenceError: mesage is not defined

Every time I work on the Discord bot code that assigns a role when activated, I encounter this error. I'm not sure if there's a hidden bug causing it, so if you spot it, please help me fix it! Error message. if(mesage.content.startsWith(prefix ...

ReactJS displays a collection of items stored within its state

I encountered an issue while trying to display a list of items in my React app with the following error message: Objects are not valid as a React child (found: [object MessageEvent]). If you meant to render a collection of children, use an array instead. ...

Is it possible to utilize a Next.js image for triggering a form submission via onClick for Google OAuth?

Disclaimer: Novice User I have successfully created a custom signin page with email and social media authentication using Next.js. Now I would like to customize the styling by incorporating Next.js/Image to replace the submit button with a clickable icon ...

How can the Header of a get-request for an npm module be modified?

Currently, I am utilizing an npm module to perform an API request: const api_req = require('my-npm-module-that-makes-an-api-request'); However, I am seeking a way to modify the user-agent used for requests generated internally by the npm module ...

Filtering an array in AngularJS based on a property that is an array data type

I am trying to filter my $scope.contracts based on the partner's name in HTML. My object structure is as follows: $scope.contracts = [ { name: "contract1", partners : [{name: "John", age:"21"}, {name: "Peter", age: "33"}] }, { name: "contrac ...

What could be causing the lack of downward rotation of my arrow in css? (specifically, the span element)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=de ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...