JavaScript - DOM Manipulation - Trying to create an <li> element once a button is clicked


As the title states, I am attempting to create what is essentially a to-do list. It isn’t going to be fancy until I learn more about js, so this is all I have so far:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <div id="container">
        <h2>To-Do List</h2>
        <input id="textArea" type="text" placeholder="Enter list item here!"><input id="submit" type="submit" value="Add">
    <div id="tasks-div">
      <ul id="tasks-list"></ul>
    <script src="script.js"></script>
:root {
  --gray: #EAEAEA;
  --blue: #029DF1;
  --white: #FFF;

* {
  margin: 0;
  padding: 0;
  text-align: center;
  margin-top: 20px;

form {
  margin-top: 0;

input {
  padding: 15px 100px;

#container {
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  background-color: var(--blue);
  padding-bottom: 20px;

#textArea {
  text-align: left;

#tasks-div {
  background-color: var(--white);
let textArea = document.getElementById("textArea");
let submit = document.getElementById("submit");
let ul = document.querySelector("ul");
let li = document.createElement("li");

//add todos
submit.addEventListener("click", function(){
  let value = textArea.value;
  li.textContent = value; 

Ideally, I want the submit feature to take the value from the textArea, append the content of the textArea to the li element, and create a list. How can I get this working properly?

1 Like

What kind of issues are you experiencing?
The code looks ok to me.

The only concern I have is that you may be adding the event listener before the DOM has actually loaded.
Have you tried wrapping it in an event listener?

// or load event
window.addEventListener('DOMContentLoaded', (event) => {
    // your code

Hope this helps :+1:

You are not preventing the default action of the form submission from happening.

To do that add a parameter to your click handler function (in the example below I named it event). Then use event.preventDefault(); at the end of your function to stop the form submission from happening.

submit.addEventListener(“click”, function(event){
let value = textArea.value;
let li = document.createElement(“li”);
li.textContent = value;

You’ll also want to move the creation of the li element into your function logic, otherwise you’ll just be changing the same element on every call.

To get a better understanding of addEventListener, the possible event handler function parameters, and preventDefault check out the Mozilla Developer Docs: