How to make a <li> using keydown of enter and .appendChild in JS?

39 Views Asked by At

I have an input text field I'd like to create a

  • in my when enter is pressed. I'm not sure where I went wrong in my code.

    Here's a snippet of the HTML I'm editing

    `<div class="day" id="monday"><div class="span"><h3 class="day-title">Monday</h3></div>
    <input type="text" class="input" id="input-area">
    <ul id='list'></ul>
    </div>`
    

    And the JS I've tried to implement

    `function addItemToList() {
    document.querySelector('input').addEventListener('keydown', function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            const input = document.querySelector('input');
            const ul = document.querySelector('ul');
            const li = document.createElement('li');
            ul.appendChild(li);
            li.innerHTML = input.value;
        }
    })
    };`
    

    Thank you for any suggestions

  • 1

    There are 1 best solutions below

    2
    Qori On

    this works just fine

    <script>
      const input = document.querySelector('input');
      const list = document.querySelector('ul');
    
      input.addEventListener('keydown', (e) => {
        if (e.keyCode !== 13) return;
    
        e.preventDefault();
        const item = document.createElement('li');
        item.innerHTML = input.value;
        list.appendChild(item);
      });
    </script>