Applying CSS to Dynamic JavaScript Elements: A Guide to Styling Without In-line Code

I'm a beginner in web development and I've been experimenting with applying styles to dynamically generated div elements using JavaScript. So far, I've only been able to manually add inline styling through this function:

function applyStyle(element) {
   style = element.style;

   style.fontSize = "16px"; 
   style.background = "#fff"; 
   style.color = "#333";
}

While this method works for individual elements, it becomes cumbersome when dealing with multiple dynamic elements that all require the same styling. I've come across suggestions stating that inline styling should be avoided and instead CSS rules should be defined in a separate file to allow for better management and reusability.
Despite my efforts to find a solution online, I have not been successful in resolving this issue. Here's a snippet of my HTML code:

<h3 id="kudos_title">Kudos</h3>
<div class="remarks"></div>

This is the JavaScript function I use to create new div elements:

function addElement (i) {
        // create a new div element
        const newDiv = document.createElement("div");

        // Add message, author, and source to content
        const content = document.createTextNode('"' + `${msg[i].remark}` + '"' + " - " + `${msg[i].author}` + " from " + `${msg[i].source}`);
        
        // add the text node to the newly created div
        newDiv.appendChild(content);

        applyStyle(newDiv, i);

        // add the newly created element and its content into the DOM
        const current_remark = document.querySelector(".remarks");

        document.body.insertBefore(newDiv, current_remark);
        
    }

Lastly, here is the CSS I am using:

#kudos_title {
    text-align: center;
    font-family: Spectral, serif;
    font-size: 50px;
}

.remarks {
    padding: 20px;
    color: pink;
    background-color: springgreen;
}

Although the heading with id=kudos_title is styled properly, the elements with the remarks class are not displaying the correct styling. It seems that the .css file is being applied to static elements, but not to dynamically generated divs using JavaScript.

Answer №1

Instead of using insertBefore, consider using appending the element inside the target. It's also recommended to use HTML entities for characters like quotes. You can see an example of this in the template literals used here. To apply specific classes, utilize element.classList.add()

let msg = [{
  remark: "test",
  author: "they",
  source: "there"
}];

function addElement(i) {
  // create a new div element
  const newDiv = document.createElement("div");
  // Add message, author, and source to content
  const content = `&quot;${msg[i].remark}&quot; - ${msg[i].author} from ${msg[i].source}`;
  // add the text node to the newly created div
  newDiv.innerHTML = content;
  newDiv.classList.add('special');
  // add the newly created element and its content into the DOM
  const current_remark = document.querySelector(".remarks");
  current_remark.append(newDiv);
}

addElement(0);
#kudos_title {
  text-align: center;
  font-family: Spectral, serif;
  font-size: 50px;
}

.remarks {
  padding: 20px;
  color: pink;
  background-color: springgreen;
}

.special {
  color: #f00;
  font-weight: bold;
}
<h3 id="kudos_title">Kudos</h3>
<div class="remarks"></div>

Answer №2

If you desire consistency in styling for all new div elements, assigning them a class and defining the styles in a CSS file is the way to go.

Consider this example: while "myclass" is used here for demonstration purposes, choose a more fitting name for your specific application:

JS

function addElement (i) {
    // create a new div element
    const newDiv = document.createElement("div");

    // Add message, author, and source to content
    const content = document.createTextNode("'" + `${msg[i].remark}` + "'" + " - " + `${msg[i].author}` + " from " + `${msg[i].source}`);
    
    // add the text node to the newly created div
    newDiv.appendChild(content);

    // add CSS class
    newDiv.classList.append("myclass");

    // add the newly created element and its content into the DOM
    const current_remark = document.querySelector(".remarks");

    document.body.insertBefore(newDiv, current_remark);
}

CSS

.myclass {
  font-size: 16px; 
  background: #fff"; 
  color: #333;
}

Answer №3

To easily style an element, simply assign a class to it during creation

JavaScript:

newDiv.className = 'bar';

CSS:

.dynamicElement{
 padding: 20px;
    color: pink;
    background-color: springgreen;
}

You have the option of using a separate CSS file for styling

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

How can I confirm that all elements have been properly reset to their original positions prior to making any further adjustments to them?

In need of some creative brainstorming, I'm working on a website design featuring ten overlapping cards. When the mouse hovers over a card, it expands while others move away. My goal is for each card to return to its original position once the cursor ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

What is the Best Way to Send JavaScript Variables to MYSQL Database with PHP?

I am having trouble sending my variable to a MySQL database. The database only displays the variable when using the HTML input tag. The error message I received was "Undefined index: rate & amount." Seeking assistance to resolve this issue. Thank you! ...

Is your YQL JSON script failing to provide the expected output?

Here is a script that I have copied almost directly from this. Why is it that the code below does not seem to return anything? ajax.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html dir="lt ...

Eliminate the array from the data retrieved through an http request in AngularJS

Currently, I am making an http call to retrieve data from a database. This process involves calling 6 different types individually. $scope.getAll = function() { var url = 'http://someurl/'; var allObjects = []; $sc ...

Updating Github pages requires clearing the cache first

As I work on my first website using GitHub pages, I've noticed that it can be frustrating to constantly clear the cache or open an incognito window whenever I add something new. I'm thinking about incorporating Jekyll into my workflow so I can t ...

What is the best way to limit the dimension of uploaded images to a specific height and width?

function validateImageDimensions(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#uploadForm + img').remove(); var img = $('<img> ...

When incorporating script tags in React, an "Unexpected token" error may arise

I am in the process of converting my website to a React site, but I am encountering an issue with the script tags not working. It keeps showing an unexpected token error. Here is the code snippet: <div className="people"> How many people are you ...

To properly display text strings in your application, ensure they are enclosed within a <Text> component in React Native. This is crucial

I recently integrated the react-native-login-screen package into my React Native project. Below is the code snippet that I used: import React, { Component } from "react"; import { Text, StyleSheet, View, Button, TouchableOpacity } from "reac ...

Encountered an issue when attempting to send data using this.http.post in Angular from the client's perspective

Attempting to transfer data to a MySQL database using Angular on the client-side and Express JS on the server-side. The post function on the server side works when tested with Postman. Here is the code snippet: app.use(bodyParser.json()); app.use(bodyPa ...

Is it possible to rearrange an array by moving an element to the front

If I have an array as shown below, how can I move key [2] and its corresponding value to the front of the array? This would make it key [0] and increment the other keys by 1. Current: [0] => Array ( [name] => Vanilla Coke cans 355ml x 2 ...

How can I target all ul elements except those contained within a div with a specific class using CSS?

In my global.scss file, I have defined global styles for ul elements as shown below: ul { list-style: none; margin: 0; padding: 0; } However, I am trying to find a way to style all ul elements except those within a specific jodit-wrapper class ...

What is the best way to eliminate the extra space above a span when the parent element's font size is very large?

Dealing with a situation where the parent DOM-element has a large em-value which results in all inline child elements having a significant margin above them despite their smaller font-size: Here is the source (http://jsfiddle.net/rapik/w87m7/2/): <div ...

Modifying the scope variable does not trigger an update in the AngularJS directive

Recently, I created a small directive that wraps its contents with another template file. The objective is to transform the code like this: <layout name="Default">My cool content</layout> into this output: <div class="layoutDefault">My ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

A common inquiry regarding Vue: How to effectively incorporate fullpage.js wrapper with additional functionalities

Having recently delved into Vue, I am currently tackling a project that involves the Fullpage.js Vue wrapper. While I have successfully implemented the Fullpage functionality, integrating additional features like an animation-on-scroll function has proven ...

XML powered jQuery menu

Admittedly, I have not yet used XML with jQuery. Below is a snippet of the XML: <folder title="Home"> <item title="Welcome" /> <folder title="My Photos"> <folder title="Holiday"> <item title="Photo 1" /> ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

The Angular filter is failing to display the category value

My issue lies in adding a filter to display categories, as my setCurrentCategory function is not showing any value but instead displaying 'undefined'. The goal is to show the category for each person. I'm using ng-click to pass to my functio ...