2012-09-27 30 views
15

Estoy intentando un ejemplo muy básico de crear un div dentro de un div ya existente.Creando un elemento div dentro de un elemento div en javascript

no parece estar funcionando cuando uso:

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

pero funciona bien cuando hago esto:

document.body.appendChild(element) 

¿Es necesario añadir windows.onload función? ¡Aunque no funciona incluso entonces!

código

HTML:

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

    <div id="lc"> 
    </div> 
</body> 

JS código:

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); 
} 
+0

Es posible que desee probar firebug: hace que sea un poco más fácil detectar errores tipográficos en su código. –

Respuesta

24

Su código funciona bien que simplemente ha escrito mal esta línea de código:

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

cambio con esto:

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

AQUÍ ES MI EJEMPLO:

<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> 
+1

Eso es claramente un error tipográfico en la pregunta. Dijo que su código funciona bien. –

+0

He agregado un ejemplo de trabajo así que creo que respondí toda la pregunta. – Develoger

+1

Dijo que funciona bien cuando se agrega al cuerpo, no a la div –

0

Sí, ya sea necesidad de hacer esto onload o en una etiqueta <script> después la etiqueta de cierre </body>, cuando el elemento lc ya se encuentra en el árbol DOM del documento.

4

' b 'debe estar en mayúscula en document.getElementById modificado co de 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); 
} 
Cuestiones relacionadas