Skip to main content

Using appendChild in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the appendChild method in JavaScript to add HTML elements to the DOM and build dynamic web pages. We'll cover the basics of the appendChild method and provide sample code with explanations.

What is appendChild?

The appendChild method is a built-in JavaScript DOM method that allows you to add a new HTML element to the DOM as the last child of a specified parent element. You can use the appendChild method to create dynamic web pages by adding new content to the DOM as needed.

Sample Code: Using appendChild

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>appendChild Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>
</body>
</html>

To use appendChild to add a new HTML element to the DOM, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can create a new button element and add it to the div element with the ID mainContainer using the appendChild method:

<!DOCTYPE html>
<html>
<head>
<title>appendChild Example</title>
</head>
<body>
<div id="mainContainer">
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
</div>

<script>
// Select the element with the ID "mainContainer"
var mainContainer = document.getElementById('mainContainer');

// Create a new button element
var newButton = document.createElement('button');

// Set the button's attributes and text content
newButton.textContent = 'Click me!';
newButton.setAttribute('id', 'myButton');
newButton.setAttribute('class', 'myButtonClass');

// Append the new button element to the main container using appendChild
mainContainer.appendChild(newButton);
</script>
</body>
</html>

After running this code, a new button element with the ID myButton and the class myButtonClass will be added to the div element with the ID mainContainer.

Live Playground, Try it Yourself

Conclusion

The appendChild method is a valuable tool for adding HTML elements to the DOM and building dynamic web pages. By mastering this method, you can create interactive and engaging web experiences that respond to user input and adapt to changing content needs.