Creating and Appending Elements
To dynamically create and append HTML elements to the DOM, you can use the following steps:
Create a new element using the
createElement
method.Set properties and attributes of the new element as needed.
Append the new element to an existing element in the DOM using the
appendChild
method.
For example, let's say we want to create a new h1
element with the text 'Hello, World!' and append it to a div
element with the id 'container'. We can do it like this:
JAVASCRIPT
1// Step 1: Create a new element
2const newElement = document.createElement('h1');
3
4// Step 2: Set properties and attributes
5newElement.textContent = 'Hello, World!';
6
7// Step 3: Append the new element
8const container = document.getElementById('container');
9container.appendChild(newElement);
This will create a new h1
element with the text 'Hello, World!' and append it as a child of the div
element with the id 'container'.
Try creating and appending elements to the DOM using JavaScript in your own project. You can use the code snippet above as a starting point.
xxxxxxxxxx
// Step 1: Create a new element
const newElement = document.createElement('h1');
// Step 2: Set properties and attributes
newElement.textContent = 'Hello, World!';
// Step 3: Append the new element
const container = document.getElementById('container');
container.appendChild(newElement);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment