Création d'un élément div dans un élément div en javascript

Je tente un exemple très simple de créer un div dans une div déjà existante.

Il ne semble pas fonctionner quand j'utilise:

 document.getElementbyId('lc').appendChild(element) 

Mais fonctionne bien lorsque je fais ceci:

 document.body.appendChild(element) 

Dois-je ajouter la fonction windows.onload ? Bien que cela ne fonctionne pas même alors!

Code HTML:

 <body> <input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" /> <div id="lc"> </div> </body> 

Code JS:

 function test() { var element = document.createElement("div"); element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); document.getElementbyId('lc').appendChild(element); //document.body.appendChild(element); } 

Votre code fonctionne bien, vous avez simplement saisi cette ligne de code:

 document.getElementbyId('lc').appendChild(element); 

Changez-le avec ceci:

 document.getElementById('lc').appendChild(element); 

ICI EST MON EXEMPLE:

 <html> <head> <script> function test() { var element = document.createElement("div"); element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); document.getElementById('lc').appendChild(element); } </script> </head> <body> <input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" /> <div id="lc" style="background: blue; height: 150px; width: 150px; }" onclick="test();"> </div> </body> </html> 

'B' devrait être en majuscule dans document.getElementById code modifié jsfiddle

 function test() { var element = document.createElement("div"); element.appendChild(document.createTextNode('The man who mistook his wife for a hat')); document.getElementById('lc').appendChild(element); //document.body.appendChild(element); } 

Oui, vous devez le faire onload ou dans une <script> après la balise </body> fermeture, lorsque l'élément lc se trouve déjà dans l'arborescence DOM du document.