js6-2

by wang_siang

HTML

<input type="text" id="textInput">
    <button onclick="add()">新增</button>
    <div id="root">
    </div>

JavaScript

var todos = [
            {
                title: "倒垃圾"
            },
            {
                title: "繳電話費"
            },
            {
                title: "採買本週食材"
            },
        ];

        function render() {
            const allList = document.createElement('ul');
            todos.forEach((item) => {
                const list = document.createElement('li');
                const span = document.createElement('span');
                const root = document.querySelector('#root');
                root.textContent = '';
                span.textContent = `${item.title}`;
                root.append(allList);
                allList.append(list);
                list.append(span);
            })
        };

        function add() {
            const textInput = document.querySelector('#textInput');
            todos.push({ title: `${textInput.value}` })
            render();
            textInput.value = '';
        };


        render();