I have two buttons. I use them to add/remove div's (class="rect"
) from the 'main' tag. I want to be able to change each of the divs' background color when clicking on it. I managed to do that for all the divs I'm creating at the first time the page loads but the function doesn't work on the new divs I add. I know it's because in my code the function is inside the onload but when i take it out it doesn't work. Any help please?
HTML:
<body>
<div id="wrapper">
<header>
</header>
<div id="buttonscontainer">
<button class="button" id="add">+</button>
<button class="button" id="remove">-</button>
</div>
<main id="main">
</main>
</div>
This is my last js attempt:
window.onload=function(){
for(var i=0;i<6;i++){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").innerHTML += rectangle;
}
document.getElementById("add").onclick = addRect;
document.getElementById("remove").onclick = removeRect;
var rectangles = document.getElementsByClassName('rect');
for(var i = 0; i < rectangles.length; i++) {
var rectangle = rectangles[i];
rectangle.onclick = function() {
this.style.backgroundColor = "red";
}
}
}
/*defines the behaviour of the addRect onclick*/
function addRect(){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").innerHTML += rectangle;
}
/*defines the behaviour of the removeRect onclick*/
function removeRect(){
var rectangle = '<div class="rect"></div>';
document.getElementById("main").lastChild.remove();
}