Appending Kittens explainer

Aim of the puzzle: Use the JavaScript .appendChild() method to add an HTML element to a page.
Walk through of solution: In a previous puzzle, you learned to use the document.createElement() method to create a new HTML element using JavaScript.

In this puzzle, you’ll use the .appendChild() method to add a new element to a page.

First, remember that HTML elements are often nested inside each other. Take a look at the following:

<html>
    <body>
        <h1>Welcome</h1>
    </body>
</html>

The <html> tag surrounds everything, with the <body> tag nested inside. Inside the <body> tag, all of the visible elements of a page are nested.

When an element is nested inside another, the nested element is referred to as a “child” of the “parent” element.

This is where the .appendChild() method gets its name. It takes an element as an argument and appends it as a child of the parent.

For example, to add a new element as a child of the body element using JavaScript, we can access the body using document.body and append the element to it, like this:

let newHeading = document.createElement('h1');
newHeading.textContent = 'New Heading';
document.body.appendChild(newHeading)

The above example creates a new h1, gives it text, and then adds it as a child of the body.

In this puzzle, 3 new elements, tilte, picture, and description, have all been created. To complete the puzzle, add them to the body using the .appendChild() method. Make sure they are added in the correct order.

Sample code solution:

JavaScript

let title = document.createElement('h1');
title.textContent = 'Cool Cat';

let picture = document.createElement('img');
picture.src = '../../static/images/catStretching.jpg';

let description = document.createElement('p');
description.textContent = 'Thank you cat, very cool!';

document.body.appendChild(title);
document.body.appendChild(picture);
document.body.appendChild(description);

Javascript Concepts: Document object, body, .createElement(), .appendChild(), .textContent