Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading