sábado, 30 de agosto de 2014

Tutorial Javascript parte 22 - createElement, appendChild, removeChild




En esta parte del tutorial veremos como crear nuevos elementos html con el método createElement(), como agregar un elemento (hijo) en el interior de otro (padre) con el método appendChild() o removerlo con el método removeChild().

El método createElement() permite crear nuevos elementos HTML.

El método appendChild() agrega un nuevo elemento html en el interior del elemento html seleccionado, este elemento se agrega justo después del último elemento html interno.

El método removeChild() elimina el elemento html seleccionado del interior del elemento html padre.

El código de ejemplo del capítulo ...


<!DOCTYPE HTML>
<html>
<head>

<script>

window.onload = function()
   {
 var button = document.createElement("button");
 button.innerHTML = "createElement";
 button.setAttribute("id", "btn");

 //document.body.appendChild(button);
 document.getElementById("contenedor").appendChild(button);
 
 var btn = document.getElementById("btn");
 btn.onclick = function()
   {
    //document.body.removeChild(btn);
    document.getElementById("contenedor").removeChild(btn);
   }
 
   }

</script>

</head>
<body>
<div id="contenedor"></div>
</body>
</html>



No hay comentarios: