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.