Home > Net >  Keep Getting an error in javascript about a node
Keep Getting an error in javascript about a node

Time:06-21

so im trying to make a list of the input from the user and i keep getting this error

html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ToDo</title>
</head>
<body>
<h1>To Do List</h1>
<label>Enter What You Have To Do:</label>
<br>
<br>
<input type="text" id="toDo">
<br>
<br>
<button type="button" id="myButton">Submit</button><br>
<ul id="list"></ul>


<script src="todojs.js"></script>
</body>
</html>

javascript

document.getElementById('myButton').onclick = function () {
const doIt = document.getElementById('toDo').value;
const li ='<li>'   doIt   '</li>';
document.getElementById('list').appendChild(li);
document.getElementById('toDo').value = '';
}

Error Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at document.getElementById.onclick

CodePudding user response:

appendChild expects a Node Element. You are passing a string. If you want to append a string, you can use the insertAdjacentHTML function.

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML/insertAdjacentHTML

document.getElementById('myButton').onclick = function () {
    const doIt = document.getElementById('toDo').value;
    const li ='<li>'   doIt   '</li>';
    document.getElementById('list').insertAdjacentHTML('beforeend', li);
    document.getElementById('toDo').value = '';
}

CodePudding user response:

const li = document.createElement("li");
li.innerHTML(doIt);

should do the trick instead of the one liner

  • Related