Skip to main content

Using createElement in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the createElement method in JavaScript to create new HTML elements and add them to the DOM. We'll cover the basics of the createElement method and provide sample code with explanations.

What is createElement?

The createElement method is a built-in JavaScript DOM method that allows you to create new HTML elements. You can use the createElement method to create an instance of an HTML element, set its attributes and content, and then add it to the DOM.

Sample Code: Using createElement

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>createElement 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 createElement to create a new HTML element and add it 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:

<!DOCTYPE html>
<html>
<head>
<title>createElement 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
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 createElement method is a powerful tool for creating new HTML elements and adding them to the DOM. By mastering this method, you can dynamically generate and manipulate content on your web pages, allowing you to create interactive and engaging web experiences.