gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
js add htnl
- User
js add htnl
- Assistant
To add HTML elements dynamically using JavaScript, you can use the
document.createElement()method to create new elements and then append them to the DOM. Here’s a simple example that demonstrates how to add HTML elements using JavaScript:Example: Adding HTML Elements Using JavaScript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Add HTML with JavaScript</title> <style> body { font-family: Arial, sans-serif; } #container { margin-top: 20px; } </style> </head> <body> <h1>Add HTML Elements</h1> <button id="addButton">Add a New Item</button> <div id="container"></div> <script> // Function to add a new item function addItem() { // Create a new paragraph element const newItem = document.createElement('p'); // Add text content to the paragraph newItem.textContent = 'This is a new item added to the list!'; // Append the new paragraph to the container document.getElementById('container').appendChild(newItem); } // Add event listener to the button document.getElementById('addButton').addEventListener('click', addItem); </script> </body> </html>