Where to load JavaScript if we are selecting elements on the page?

Always load it before the closing body tag (</body>). It is because, we need to have all elements before we start selecting them in JavaScript. We get null if we try to grab elements placing the <script> tag in the head because the elements are not yet created when the JavaScript is run.

Other option: (to use in <head> tag)

Best way: Load the JS before the </body> tag.

In querySelector and querySelectorAll, the argument we pass is nearly similar to CSS Selectors.

We can use things like:

<div class="items">
	<div class="item item1">
		<img src="<http://img1.com>" >
	</div>
	<div class="item">
		<img src="<http://img2.link>" >
	</div>
</div>

In above HTML, suppose if we want just the first item and find the image inside of the item.

We have 2 options:

  1. document.querySelector('item img');
const item1 = document.querySelector('.item1');
const item1Img = item1.querySelector(img); //important