Explanation of how .children property works

Hi, in this post I’m going to explain you what is the property .children and also what is the main functionality of this property.

Nice, so the .children is a property (read-only, this mean that you cannot modify the result of this) and return us a live HTMLCollection that contains all the child elements of the node that was called.

So, for example if I have this HTML DOM tree:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>.children property</title>
        <meta name="viewport" content="width=device-width">
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>

        <section id="mySection">
            <article>This is my Article 1</article>
            <article>This is my Article 2</article>
            <article>This is my Article 3</article>
        </section>

        <script src="testing.js"></script>
    </body>
</html>

Result:

Then in our Javascript we are going to get the element to later know what children’s it has, in this case the <section></section> element

const sectionElement = document.getElementById('mySection'); // Getting the node
console.log('sectionElement is the element --->', sectionElement); // the node is type Element 

Result:

Then we can use the .children property to know which are the children elements that <section></section> element have:

const sectionElement = document.getElementById('mySection'); // Getting the node

console.log('sectionElement.children ---->', sectionElement.children); // the element has these children's

Result: Nice! our <section></section> element have 3 children’s!

Cool, but what about if one or two <article></article> element have more elements? the .children property will count that children’s too? hmm, let’s see:

        <section id="mySection">
            <article>This is my Article 1</article>
            <article>
                <p>This is my Article 2</p>
                <h1>Thanks for visit learn tech systems!</h1>
            </article>
            <article>This is my Article 3</article>
        </section>

Javascript: is the same logic nothing changed

const sectionElement = document.getElementById('mySection'); // Getting the node
console.log('sectionElement is the element --->', sectionElement); // the node is type Element 

console.log('sectionElement.children ---->', sectionElement.children); // the element has these children's

Result: The result is the same because we are getting only the children’s of the <section></section> element and and that’s it! sectionElement.children

So, .children property will return us ALL THE CHILD ELEMENTS OF THE NODE THAT WAS CALLED.

By Cristina Rojas.