Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

javascript - How to style dynamically created elements with CSS

I'm trying to make an APP, which allows me to add days to a table

I have the following Code

function addDay() {

for (k = 1; k < 11; k++) {
    let div = document.createElement("div");
    div.style.background = "red"
    div.style.color = "white"
    div.style.width = "40px"
    div.style.height = "20px"
    div.style.margin = "0.5px"
    div.style.textAlign = "center"
    div.style.borderRadius = "6px"
    div.setAttribute("class", "studentGrades")
    // div.setAttribute("class", "sgID" + k)
    div.className += " sgID" + k
    div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");

    div.innerHTML = "0"

    document.querySelector("#container3").appendChild(div)
}} 

This works perfectly fine for me, But I also have to make a Responsive design for this app, so on a smaller screen,

These properties are too big,

    div.style.width = "40px"
    div.style.height = "20px"

I need something like ,

    div.style.width = "20px"
    div.style.height = "10px"

So here is the problem, These elements are dynamically created, They are not present when HTML is loaded, So I can't style them with CSS, Is it Possible to style those elements via CSS? And if yes how?

This is on a big screen, Add day button adds 1 green and 10 red boxes

Same here, except i want those boxes to be smaller (same size as the boxes next to it)

P.S

I'm into a 3rd week of my coding adventure, I'm familiar with only Vanilla JS, So no Library/Framework's.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make a class and add that class to created elemets.

Example:

for (k = 1; k < 11; k++) {
    let div = document.createElement("div");
    div.setAttribute("onclick", "averageFunc(this, Number(prompt('Please, enter number here')))");
    div.className = 'custom-class';
    div.innerHTML = "0"
    document.getElementById("container3").appendChild(div)
}
.custom-class {
  background : red;
  color: white;
  width : 20px;
  height : 20px;
  margin-top :2px;
  text-align : center;
  border : 1px solid black;
}
<div id="container3"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...