简体   繁体   中英

Adding a string item to an appendChild li element

here's my code:

<!DOCTYPE html>
<html lang="en">
<head>
<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">
<title>Todo-List</title>
</head>
<body>
<div id="container">
  <header>
    <h2>To-Do List</h2>
  </header>
  <input id="textArea" type="text" placeholder="Enter list item here!"><input id="submit" type="submit" value="Add">
</div>
<div id="tasks-div">
  <ul id="tasks-list"></ul>
</div>
<script src="script.js"></script>

let textArea = document.getElementById("textArea");
let submit = document.getElementById("submit");
let ul = document.querySelector("ul");
let deleteIcon = document.createTextNode(" X ");

//add todos
let addTodos = submit.addEventListener("click", function() {
let value = textArea.value;
let li = document.createElement("li");
li.textContent = value;
let listItem = ul.appendChild(li);
for (var i = 0; i < listItem.length;i++){
  li += " X ";
}
textArea.value = "";
});

I thought by using the += operator, it would add that X to any li element. How would I go about this to ensure that when an li element is created, it has a " X " at the end of it?

Change this line

li.textContent = value;

To this

li.innerHTML = `${value} <button>X</button>`;

Then remove that for loop

Demo here https://jsfiddle.net/sawyerrken/ze8f5dnu/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM