Introduction and Topic Overview

Welcome! Today's mission is to supercharge our webpages with JavaScript! We'll master the art of creating new HTML elements, setting their attributes, and dynamically swapping the content. Are you ready? Let's dive in!

Understanding DOM and its Interaction with JavaScript

The DOM (Document Object Model) structures a webpage much like a family tree. JavaScript manipulates the DOM to transform your webpage.

<!DOCTYPE html>
<html>
<head>
    <title>Our Web Page</title>
</head>
<body>
    <h1>Welcome to our web page!</h1>
</body>
</html>

Our webpage currently holds a welcome message. Let's jazz it up with JavaScript!

Creating New Elements in HTML via JavaScript

JavaScript is used to create new HTML elements with the document.createElement() function. Here's how we do it:

<body>
    <h1>Welcome to our web page!</h1>
    <script>
        let newElement = document.createElement("p");
        newElement.innerHTML = "This is a new paragraph.";
        document.body.appendChild(newElement);
    </script>
</body>

This document.createElement("p") spells into existence a new paragraph element, currently an empty shell <p></p>. It's almost like having an actor for our play (the webpage) but without lines to say. To affix content, newElement.innerHTML = "This is a new paragraph." embeds text within our ledged element, breathing life into it as <p>This is a new paragraph.</p>.

With our new element all set to join the webpage script, document.body.appendChild(newElement), makes its grand entry. The appendChild() function, you see, is like a stagehand who ushers the new element into its spot in the webpage. The new element relaxes into its position as the last child of the parent element. Here, document.body is our parent element being the body of our webpage. The newly-birthed paragraph becomes the last child of our body element, perfectly settling into the webpage.

If in an instance, you need to append a new child to a different parent element, a div or a span, you can pluck that parent using 'document.getElementById'. And then, the new element can make its entry. For example we can use document.getElementByID('someId').appendChild(newElement); to append the new element to our existing element with ID #someId. A versatile stagehand indeed!

And there you have it! We've created, brightly lit, and stationed a new paragraph element on our webpage using JavaScript.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal