Reputation: 11
I want to click on a button adding a div to the id container with different color backgrounds if odd or even. This is the code i wrote. I tried to use an if statement with a modulo inside a for loop. nextDiv e Nextdiv2 have the two different backgrounds.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<section id="container">
<button id="button">Clicca qui</button>
<div class="divs"></div>
</div>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var container = document.getElementById("container");
var button = document.getElementById("button");
var divs = document.getElementsByClassName("divs");
button.addEventListener("click", AddDiv);
function AddDiv() {
nextDivs = document.createElement("div");
nextDivs.setAttribute("class", "nextDiv");
container.appendChild(nextDivs);
}
for(i = 0; i < container.length; i++) {
if(i % 2 !== 0){
nextDivs.ClassList.add("nextDiv");
}
nextDivs.classList.remove("nextDiv2");
}
thank you
Upvotes: 0
Views: 52
Reputation: 54
I created a variable to count the total of divs were created and use it to calc if the next div will use nextDiv or nextDiv2.
let container = document.getElementById("container");
let button = document.getElementById("button");
let divs = document.getElementsByClassName("divs");
button.addEventListener("click", AddDiv);
let countDivs = 0;
function AddDiv() {
nextDivs = document.createElement("div");
if (countDivs % 2 === 0){
nextDivs.setAttribute("class", "nextDiv");
} else {
nextDivs.setAttribute("class", "nextDiv2");
}
countDivs++;
container.appendChild(nextDivs);
}
.nextDiv, .nextDiv2{
width: 300px;
height: 50px;
}
.nextDiv{
background-color: #242424;
}
.nextDiv2{
background-color: #de2121;
}
button{
margin-bottom: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<section id="container">
<button id="button">Clicc aqui</button>
<div class="divs"></div>
</section>
</body>
</html>
Upvotes: 1
Reputation: 251
you must count how many divs you have inside your container so, when you add one you know if you have an odd or even quantity and thus place the class
var button = document.getElementById("button");
button.addEventListener("click", AddDiv);
function AddDiv() {
var container = document.getElementById("container");
var nextDivs = document.createElement("div");
if (container.getElementsByTagName('div').length % 2 == 0) {
nextDivs.setAttribute("class", "even");
} else {
nextDivs.setAttribute("class", "odd");
}
container.appendChild(nextDivs);
}
.odd {
background-color: red;
width: 10px;
height: 10px;
}
.even {
background-color: yellow;
width: 10px;
height: 10px;
}
<section id="container">
<button id="button">Clica qui</button>
</section>
Upvotes: 0