.appendChild() method to add an HTML element to a page.
Walk through of solution: In a previous puzzle, you learned to use the
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>
<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
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
In this puzzle, 3 new elements,
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:
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);