This is the full code using constant number and it works. ( If I click 'text 2' the box is moved.)
<!DOCTYPE html>
<html>
<head>
<style>
.myDIV {
position: relative;
width: 100px;
height: 100px;
background-color: coral;
color: white;
}
</style>
</head>
<body>
<div class="text">text 1</div>
<div class="myDIV"></div>
<div class="text">text 2</div>
<div class="myDIV"></div>
<script>
var texts = document.getElementsByClassName("text");
var boxes = document.getElementsByClassName("myDIV");
texts[1].onclick = function(e){
boxes[1].style.top = "100px";
}
</script>
</body>
</html>
But after I changed the constant '1' to variable'i' in the javascript, it doesn't work. I think there is some error in my code, but I don't know what it is.
<script>
var texts = document.getElementsByClassName("text");
var boxes = document.getElementsByClassName("myDIV");
for(var i = 0; i < texts.length; i++)
texts[i].onclick = function(e){
boxes[1].style.top = "100px";
}
</script>