@daisha
In JavaScript, you can dynamically create elements using the createElement method and add them to the DOM (Document Object Model) using various techniques.
Here's a step-by-step guide to dynamically create elements in JavaScript:
Here's an example that demonstrates the above steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Step 1: Select the parent element
const parentElement = document.getElementById('parent');
// Step 2: Create a new element
const newElement = document.createElement('div');
// Step 3: Add attributes to the new element
newElement.setAttribute('class', 'my-class');
// Step 4: Add content to the new element
newElement.innerHTML = "Some content";
// Step 5: Append the new element to the parent element
parentElement.appendChild(newElement);
|
This example dynamically creates a div element with the class name "my-class" and a text content of "Some content", then appends it to the parent element with the id "parent".