0
I’m trying to pass the array elements with for( of ) to the html elements I created by js. The problem is that when I try to put the created in js inside, using appendchild, the error code.
That’s the javascript:
var listElement = document.querySelector('#app ul');
var inputElement = document.querySelector('#app input');
var buttonElement = document.querySelector('#app button');
var todos = [
'Fazer café',
'Estudar Javascript',
'Lavar a Louça'
];
function renderTodos(){
for(todo of todos){
var todoElement = document.createElement('li');
var todoText = document.createTextNode(todo);
todoElement.appendChild(todoText);
listElement.appendChild(todoElement);
}
}
renderTodos();
That’s the html;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content Language" content="pt-br">
<title>Parte 3</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="app">
<ul>
</ul>
<input type="text" placeholder="Digite um To do">
<button>Adicionar</button>
</div>
</body>
</html>
Error occurred:
script.js:18 Uncaught Typeerror: Cannot read Property 'appendchild' of null at renderTodos (script.js:18) at script.js:22
What error message? I copied the code in Jsfiddle worked normally.
– Yves Cavalcanti
script.js:18 Uncaught Typeerror: Cannot read Property 'appendchild' of null at renderTodos (script.js:18) at script.js:22
– Carlos Storari
Your script should be running before the DOM is ready, so the <ul> does not yet exist, put the script after the tag </body>.
– Yves Cavalcanti