Problem with simple javascript [ NOT SOLVED ]

I’m working on the portfolio project here.

<div class="portfolio-wrapper">
			<div>Portfolio</div> <!-- Just a title. Below are divs soon to contain images -->

I want to use javascript to assign every div after the first in the portfolio wrapper div a new class, as to keep my html a bit more DRY and for the learning experience. Here’s my JS

let portfolioDivs = document.querySelectorAll('.portfolio-wrapper > div');


The console tells me the length of portfolioDivs is 0. Why?

The code is fine, did you copy it exactly?

Example from this forum’s code (you can try it in the console):

document.querySelectorAll('.topic-body > div').length

Where did portfolio-divs come from all of a sudden?

Ok this is better in the console

document.querySelectorAll('.portfolio-wrapper > div');
NodeList(7) [div,,,,,,]

But it still doesn’t solve my problem because that was in my original code anyway

Ok this is downright strange. I put this in my JS file.

let portfolioDivs = document.querySelectorAll('.portfolio-wrapper > div').length;


The console then prints out 0.

If I go into the console and physically input this:

portfolioDivs = document.querySelectorAll('.portfolio-wrapper > div').length;

It returns 7!

Why?!?! Does it have something to do with the ‘let’?

OK GUYS I found the answer but I’m still confused a bit.

I was having that problem above, then I moved the tag from the head of my HTML to the end of the body. What kind of effect would this have on how the JS runs?

I guess you didn’t delay it, call it only once the document was loaded, the DOM constructed. So it didn’t have the divs to look at yet.

1 Like