Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML

Uncaught TypeError: document.querySelector(...) is null

I'm following a tutorial, and write the exact same code as the tutor, but i get this error in the console: "Uncaught TypeError: document.querySelector(...) is null". Here is the code, and I get an error message on the line " document.querySelector('.pepsi').src = anything;".

<script type="text/javascript">

function imgSlider(anything){

document.querySelector('.pepsi').src = anything;

}

</script>

This code is linked(?) to this code some lines above:

<ul class="thumb">

<li><img src="pepsi001.png" onclick="imgSlider('pepsi001.png')"></li>

<li><img src="pepsi002.png" onclick="imgSlider('pepsi002.png')"></li>

<li><img src="pepsi003.png" onclick="imgSlider('pepsi003.png')"></li>

</ul>

The "pepsi" pictures in the code is saved in the same folder as I have saved the HTML and CSS file. I use an external SSD (I'm using mac) to store my coding files. What I'm trying to achieve is that the big pepsi bottle change color when clicking on one of the small pepsi bottles, as you can see here: https://youtu.be/s_z5laE4KTw?t=620 . Any help is appreciated!

Michael Cook
Michael Cook
2,125 Points

You are trying to select an element with the class name pepsi, but you haven't added that class to any of your HTML elements.

1 Answer

Tomas Schaffer
Tomas Schaffer
11,606 Points

Hi first problem is described that is you dont setting class names on elements, second problem is. When you selecting elements by class you dealing always with array or list of elements, even if you have only one element with this class name. If you use id you get only one element. so in your case you have to set also index or if you want to modify all elements use some loop.

document.querySelector('.pepsi')[0].src or use loop