intermediate
Create Element Dynamically
Create and append new HTML elements using JavaScript.
Learn document.createElement and appendChild.
📚 Concepts & Theory
Creating Elements
const div = document.createElement('div');
div.textContent = 'New content';
parent.appendChild(div); 🎯 Your Challenge
Create a new paragraph and add it to the page.
📝 Starter Code
JavaScript
// HTML: <div id="container"></div>
function addParagraph(text) {
// Your code here
}
Solution
JavaScript
function addParagraph(text) {
const p = document.createElement('p');
p.textContent = text;
document.getElementById('container').appendChild(p);
}
addParagraph('Hello World');
Explanation
Create element, set content, append to DOM.
❓ Frequently Asked Questions
append accepts strings too