javascriptjqueryhtmlchildrenoffsetwidth

Why am I getting a cannot read property message in my console when I try to use children property and offsetWidth?


I am new to coding and programming and I have been following, on Youtube, a screen recording of a programmer making a responsive thumbnail slider using HTML, CSS, and Javascript. I've gotten to a point where I am trying to check if my Javascript was logged into the console, but I continue to get this error message: "script.js:3 Uncaught TypeError: Cannot read property 'children' of null at script.js:3" Commenting line 3 solves the problem but then the same error shows for line 4: "script.js:3 Uncaught TypeError: Cannot read property 'offsetWidth' null at script.js:4"

Can someone tell me why this is happening? My code is below.

const container=document.querySelector(".thumbnail-container");
	const allBox=container.children;
	const containerWidth=container.offsetWidth;
	const margin=30;
	var item=0;
	
	
	// item setup per slide
	
	responsive=[
	{breakPoint:{width:0,item:1}}, //if width greater than 0 (1 will item show)
	{breakPoint:{width:600,item:2}}, //if width greater than 600 (2 will item show)
	{breakPoint:{width:1000,item:4}} //if width greater than 1000 (4 will item show)
	]
	
	function load(){
		for(let i=0; i<responsive.length;i++){
			if(window.innerWidth>responsive[i].breakPoint.width){
				items=responsive[i].breakPoint.item
			}
		}
		start();
	}
	
	function start(){
		for(let i=0;i<allBox.length;i++){
			//width and margin setup of items
			//allBox[i].style.width=containerWidth/items;
			console.log(allBox[i])
		}
	}
	
	window.onload=load();
<div class="thumbnailslider">
			<div class="thumbnailcontainer">
				<div class="artitem">
				1
				</div>
				<div class="artitem">
				2
				</div>
				<div class="artitem">
				3
				</div>
				<div class="artitem">
				4
				</div>
				<div class="artitem">
				5
				</div>
				<div class="artitem">
				6
				</div>
				<div class="artitem">
				7
				</div>
				<div class="artitem">
				8
				</div>
			</div>
			
			<!-- Control Slides -->
			<div class="artcontrols">
				
			</div>
		</div>
		<script src="script.js"></script>
		


Solution

  • Please change this line you have misspelled thumbnailcontainer to thumbnail-container

    const container=document.querySelector(".thumbnailcontainer");