I cant give a style with js to the starLoc Const
i get this error:
script.js:14 Uncaught TypeError: Cannot read properties of undefined (reading ‘style’)
at starMove (script.js:14:20)
const btn = document.getElementById('btn');
const star = document.querySelector('.space');
const starLoc = document.querySelectorAll('.star-obj');
var rndLeft = Math.floor(Math.random()*1000);
var rndTop = Math.floor(Math.random()*1000);
function startSpacing(){
btn.style.display = 'none';
starMove();
}
function starMove(){
for(var i = 0; i <= 60; i++){
star.innerHTML += '<div class="star-obj">*</div>';
starLoc[i].style.left = rndLeft + 'px'; //14 line
starLoc[i].style.top = rndTop + 'px';
}
}
<body>
<div class="start">
<button id="btn" onclick="startSpacing()">Start Space Moving</button>
</div>
<div class="space"></div>
<script src="script.js"></script>
</body>
what is wrong with const?
Do not judge strictly, I’m a beginner
>Solution :
First, in your HTML you call startSpacing() while the function name is starMove(). Second, you dynamically generate elements, so you need to get them every time the function is called. This means moving starLoc to the function. See the example with color: red;
const star = document.querySelector('.space');
let rndLeft = Math.floor(Math.random() * 1000);
let rndTop = Math.floor(Math.random() * 1000);
function starMove() {
for (let i = 0; i <= 60; i++) {
star.innerHTML += '<div class="star-obj">*</div>';
let starLoc = document.querySelectorAll('.star-obj');
starLoc[i].style.color = 'red';
}
}
<div class="start">
<button id="btn" onclick="starMove()">Start Space Moving</button>
</div>
<div class="space"></div>