Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html> <head> <title>Adding Elements</title> </head> <body> <div id="task-list"> <h2>Task List</h2> <ul id="tasks"> <li>Initial task</li> </ul> <input type="text" id="new-task" placeholder="New task"> <button id="add-task">Add Task</button> <button id="insert-before">Insert Before First Task</button> </div> <script> const taskList = document.getElementById('tasks'); const newTaskInput = document.getElementById('new-task'); const addTaskButton = document.getElementById('add-task'); const insertBeforeButton = document.getElementById('insert-before'); addTaskButton.addEventListener('click', () => { const newTaskText = newTaskInput.value; if (newTaskText.trim()) { const newTask = document.createElement('li'); newTask.textContent = newTaskText; taskList.appendChild(newTask); newTaskInput.value = ''; } }); insertBeforeButton.addEventListener('click', () => { const newTaskText = newTaskInput.value; if (newTaskText.trim()) { const newTask = document.createElement('li'); newTask.textContent = newTaskText; const firstTask = taskList.firstChild; taskList.insertBefore(newTask, firstTask); } }); </script> </body> </html>