Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

285
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda