2 ways to get child elements with JavaScript

Image for post
Image for post

Let’s start with a simple webshop page.

<header class="product__list-header">
<h2>Webshop</h2>
</header>
<section class="product__list">
<div class="product__item">
<img src="http://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item fun__class">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
<div class="product__item">
<img src="https://lorempixel.com/400/200/food" class="product__image" alt="Food">
<span class="product__price">500</span>
</div>
</section>

#1 element.children

var productList = document.querySelector('.product__list').children;
console.log('productList: ', productList);
for (i = 0; i < productList.length; i++) {
console.log('productList[i]: ', productList[i]);
}

#2 document.querySelectorAll

var productList = document.querySelectorAll('.product__list .product__item');
console.log('productList: ', productList);
for (i = 0; i < productList.length; i++) {
console.log('product: ', productList[i]);
}

Conclusion: element.children VS querySelectorAll

Video resources

Written by

I write stories about Frontend Dev, JavaScript, Typescript, Angular, NodeJS, Serverless Functions, JAM Stack, FaunaDB, Netlify, Apple, iOS— https://byrayray.dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store