¿Cómo agregar Divs dinámicamente uno al lado del otro usando javascript usando bucles?
Frecuentes
Visto 2,458 veces
2
¿Puede ayudarme a agregar Divs uno al lado del otro usando javascript usando bucles, aquí dos columnas y 6 filas? Probé el siguiente código,
for(var i=0;i<2;i++) {
for(var j=0;j<5;j++) {
document.write('<div style="width:200px;height=200px;border:1px solid red;float:left" />')+"\n";
}
}
5 Respuestas
2
html:
<div id="table"></div>
js:
var newdiv;
for(var i=0;i<2;i++) {
for(var j=0;j<6;j++) {
newdiv=document.createElement("div");
newdiv.style.width = '80px';
newdiv.style.height = '80px';
newdiv.style.border = '1px solid red';
newdiv.style.float = 'left';
document.getElementById('table').appendChild(newdiv);
}
newdiv=document.createElement("div");
newdiv.style.clear = 'both';
document.getElementById('table').appendChild(newdiv);
}
Respondido 29 ago 12, 15:08
0
Creo que has agregado el "\n"
en lugar equivocado
document.write('<div style="width:200px;height=200px;border:1px solid red;float:left" />'+"\n");
Código probado:-
function CreateDiv()
{
for(var i=0;i<2;i++) {
for(var j=0;j<5;j++) {
document.write('<div style="width:200px;height=200px;border:1px solid red;float:left" >Hi</div>');
}
}
}
Respondido 29 ago 12, 15:08
0
Parece funcionar, echa un vistazo: http://jsfiddle.net/fCSTp/1/
var i = 0, div,
node = document.createElement("div"),
main = document.getElementById("main");
while (6 > i++) {
div = node.cloneNode(true);
div.innerHTML = i;
div.style.cssText = "width:200px;height:20px;float:left;border:1px solid red";
main.appendChild(div);
}
delete node;
delete div;
Respondido 29 ago 12, 16:08
0
Prueba esta
HTML
<div id="table"></div>
CO
#table .box {
width: 100px;
height: 30px;
background-color: #ccc;
}
#table .box:nth-child(even) {
background-color: #eee;
}
#table .col {
width:100px;
border: 1px solid #aaa;
float: left;
}
JS
makeTable();
function makeTable() {
var table = document.getElementById("table");
var row ='';
for(var i=0;i<2;i++)
{
for(var j=0;j<6;j++)
{
row += "<div class='box'></div>";
}
table.innerHTML += "<div class='col'>"+row+"</div>";
row ='';
}
}
Respondido el 17 de enero de 14 a las 22:01
-1
Insertar un <br style="clear:both"/>
al final de cada fila:
for(var i=0;i<2;i++) {
for(var j=0;j<5;j++) {
document.write('<div style="width:200px;height=200px;border:1px solid red;float:left" />')+"\n";
}
document.write('<br style="clear:both"/>');
}
Respondido 29 ago 12, 15:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript or haz tu propia pregunta.
¿No es esto más un problema de CSS en lugar de un problema de JS? También por favor no use
document.write()
. - PeeHaafunciona - jsfiddle.net/h3NMn - Zoltan Toth
¿Quizás deberías usar una mesa? - Waleed Khan
Eso produciría dos filas y cuatro columnas, pero por la forma en que está escrito [menos el error \n] sería una fila hasta que se ajusta en el navegador. - epascarello
@ZoltanToth intenta cambiar la resolución .. - Mihai Iorga