// Get a reference to an existing parent element const parentElement = document.getElementById('container'); if (parentElement) { // 1. Create a new div element const newDiv = document.createElement('div'); // 2. Set its text content newDiv.textContent = 'This is a dynamically created element!'; // 3. Add a class for styling (optional) newDiv.classList.add('dynamic-item'); // 4. Set an attribute (e.g., a data attribute) newDiv.setAttribute('data-id', '123'); // 5. Append the new div to the parent element parentElement.appendChild(newDiv); console.log('New element appended:', newDiv); } else { console.error('Parent element with ID "container" not found.'); } /* HTML structure for testing:
Existing content