JScript Selectors HELP 😭😭

JScript Selectors HELP :sob::sob:
0.0 0

#1

Im really having a great bad time when using JS Selectors! Before anything else, Heres my Code!

<body>
	<div class="container">
		<div class="square"></div>
		<div class="square"></div>
		<div class="square"></div>
		<div class="square"></div>
		<div class="square"></div>
		<div class="square"></div>
	</div>
</body>

var colors = [
"rgb(255 , 0 , 0)",
"rgb(255 , 255 , 0)",
"rgb(0 , 255 , 0)",
"rgb(0 , 255 , 255)",
"rgb(0 , 0 , 255)",
"rgb(255 , 0 , 255)",
];

var squares = document.getElementsByClassName("square");
alert(squares.length)

That is my code in my scripts.js! so when i try to open the webpage, it alerts 0, yeah 0 instead of the real length of the Divs which is 6, but when i play with the console typing this:

squares.length;

It returns 6, which is cool! Whats wrong!?


#3

at the top, header basically! I see youre a filipino as well!


#4

Oh! Yeah! it worked, But Why? If you dont mind, Can you please explain this matter further to me?


#5

You were calling your script before the DOM content was fully loaded, hence the length of 0.

You can adopt different strategies in order to make sure your scripts are executed before/after the page is fully loaded and “ready” to be used.


#6

Oh I See! Thanks I’ve been coding JS since a week ago, i never thought this exists…LOL