Its a project for adding pictures and i want to create more picture loading boxes before the add box when the button with ‘add’ class is pressed. When the button is pressed the console log works but the change of innerHTML doesnt. As i am a beginner i would appriciate any comments that can improve my work as im trying to learn and grow everyday. thank you!
here is the html, css and js:
const container = document.getElementsByClassName('container')
const add = document.getElementsByClassName('add')
function addMore(){
container.innerHTML += `
<div class="box upload">
<div class="cir">
<i class="fa-solid fa-upload fa-2xl" style="color: #ffffff;"></i>
</div>
</div>
`
console.log('done')
}
body {
background: rgb(112,50,154);
background: linear-gradient(158deg, rgba(112,50,154,1) 9%, rgba(29,126,253,1) 100%);
margin: 0;
padding: 0;
display: flex;
}
.container {
height: 100vh;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
flex-flow: wrap;
}
.box{
background-color: rgb(100, 0, 100);
border: 1px solid rgb(183, 79, 183);
border-radius: 10px;
width: 157px;
height: 200px;
margin: 10px 10px 10px 10px ;
display: flex;
justify-content: center;
align-items: center;
}
.add {
opacity: 70%;
}
.cir {
background-color: rgba(250, 235, 215, 0.408);
width: 100px;
height: 100px;
border-radius: 70px;
display: flex;
justify-content: center;
align-items: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>App</title>
<script src="https://kit.fontawesome.com/9f2b728e62.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<div class="box upload">
<div class="cir">
<i class="fa-solid fa-upload fa-2xl" style="color: #ffffff;"></i>
</div>
</div>
<button class="box add" onclick="addMore()">
<div class="cir">
<i class="fa-solid fa-plus fa-fade fa-2xl" style="color: #ffffff;"></i>
</div>
</button>
</div>
</body>
</html>
2
Answers
document.getElementsByClassName() returns an HTMLCollection which is accessed like an array. You want to modify the first element in that array like this:
getElementsByClassName
returns an array like objectmore info about it here getElementsByClassName
You have to access the element by its index so add [0] to it since you only have one element with that class so you have to access that element like this
or in this case is better if you use querySelector instead
Edit: Edited the HTML to have your button at the beggining and your first div right next to it (it looks better)