Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
How to Apply CSS to Dynamic JS Elements without In-line Styling

I'm new to web development and I've been trying to apply styling to div elements that are generated using javascript, but I've only been able to do this manually using the following function:

function addStyle(element) {
   rem = element.style;

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

This works fine for individual elements, but there might be potentially dozens of dynamic elements created which all must include the same inline styling. I've read elsewhere that apparently this is not a good practice and should be avoided if possible. Thus, I would prefer that these css rules are defined in a separate file so that I can potentially access them for other elements as well.
However, I have been unable to find a solution anywhere online no matter how similar their issue may seem. Here's my relevant HTML code:

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

My JS to create new div element:

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);

        addStyle(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, the CSS:

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

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

I should mention that the heading with id=kudos_title is successfully styled, but anything part of the remarks class is not. So clearly the .css file is being recognized for static elements, but JS created divs are not.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You are using insertBefore which will insert the element before the target (thus NOT inserting inside it). Try appending instead. Additionally, it's best practice to use HTML entities for things like quotes in text, so I used them here, showing how you can combine your string using your template literals. To add certain classes, use 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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want all the new divs to be styled in the same way, you can just give them a class and then define those styles in a CSS file.

You can do it like this: note that the name "myclass" is given purely for illustration, I'm sure you can come up with a meaningful name that works for your 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;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Just use a class and include it when making the element

JS:

newDiv.className = 'bar';

CSS:

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

You can just use a css file

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda