Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to give a random style (top/left) to the const with queryselector?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading