You're given some existing HTML for a Todo List app. Add the following functionality to the app:
<input> field should be cleared upon successful addition.ids, data attributes, replacing some tags, etc.), but the result should remain the same visually.1<!doctype html>2<html>3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 </head>7 <body>8 <div>9 <h1>Todo List</h1>10 <div>11 <input12 aria-label="Add new task"13 type="text"14 placeholder="Add your task" />15 <div>16 <button id="submit">Submit</button>17 </div>18 </div>19 <ul>20 <li>21 <span>Walk the dog</span>22 <button>Delete</button>23 </li>24 <li>25 <span>Water the plants</span>26 <button>Delete</button>27 </li>28 <li>29 <span>Wash the dishes</span>30 <button>Delete</button>31 </li>32 </ul>33 </div>34 <script src="src/index.js"></script>35 </body>36</html>
There are a few ways to approach this question:
<template>s and render both initial and new tasks client-side. See solution.The rendered list is the source of truth, so adding and deleting tasks uses direct DOM operations rather than a parallel state array. New labels are assigned with textContent, which displays potentially malicious input as text instead of interpreting it as HTML.
One listener handles submission and a delegated list listener handles every current or future Delete button. These page-lifetime listeners need no component teardown in this example. Native buttons retain keyboard behavior, and the input's accessible label is covered below.
When rendering user input, there's a risk of inserting potentially malicious content resulting in cross-site scripting (XSS). To prevent XSS:
Element.innerHTML; set Node.textContent instead, which inserts strings as raw text rather than parsing them as HTML.<input>s should be labeled either via <label>s or aria-label attributes. Since the original markup doesn't contain a <label>, we can add aria-label to the <input>.aria-live region can be added to inform them about the newly added task. There is unlikely to be enough time to do this during an interview, but you will get bonus points for mentioning it. Read more about ARIA live regions on MDN.<script>, <style>, or <link>) and ensure there's no XSS.<input> is cleared after a task is added.console.log() statements will appear here.