Understanding DOM element children property in JavaScript function

I’m working on a simple image carousel and I’m having trouble understanding how the DOM children property works with function parameters.

Here’s my code:

<!DOCTYPE html>
<html>
<head>
    <title>Photo Gallery</title>
</head>
<body>
    <div id="gallery">
        <img src="image1.jpg" alt="Mountain" />
        <img src="image2.jpg" alt="Ocean" />
        <img src="image3.jpg" alt="Forest" />
        <img src="image4.jpg" alt="Desert" />
        <img src="image5.jpg" alt="City" />
    </div>

    <script>
    var photoCarousel = function(wrapper) {
        this.photos = [];
        this.currentPhoto = 0;
        for (j = 0; j < wrapper.childElementCount; j++) {
            this.photos.push(wrapper.children[j]);
            this.photos[j].style.display = "none";
        }
    }
    </script>
</body>
</html>

What I don’t understand is how the wrapper parameter connects to the actual DOM element. When I use wrapper.children, how does JavaScript know which elements to target? I see there are multiple elements in the HTML, but somehow it only considers the img tags as children. Can someone explain this relationship?

yep, totally get it! the wrapper is like a placeholder. when u pass the #gallery div, wrapper.children just grabs the img tags inside that div. so that’s why only those are counted as children.

The connection happens when you call the function and pass in a DOM element. Your code shows the function definition but not where you actually use it. You’d need something like var carousel = new photoCarousel(document.getElementById('gallery')); to make it work. When you pass document.getElementById('gallery') as the argument, that becomes the wrapper parameter inside your function. The children property returns an HTMLCollection of direct child elements - in your case, the img tags. JavaScript doesn’t magically know what to target. You tell it by passing the specific DOM element when calling the function.

Think of it this way - the wrapper parameter is just a variable holding whatever DOM element you pass in when you create the function. Here’s what you’re missing: children only returns HTML elements, not text nodes or whitespace. Even if there’s whitespace between your img tags in the HTML, the children property filters that out automatically and only gives you actual element nodes. That’s why you only get the img tags despite spacing in your markup. childElementCount works the same way - it counts only element nodes, not all child nodes. If you used childNodes instead, you’d get text nodes too and mess up your count.