Estoy creando un script para reorganizar los elementos <div>
en una página. Puede ponerlos en una matriz, pero el contenido de esa matriz se ve así:
[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],[object HTMLDivElement],
Ninguno de los siguientes ha funcionado:
my_array.innerHTML
my_array.outerHTML
my_array.html
my_array.toString()
Entonces, ¿cómo puedo recuperar esta matriz en algo que se parece a: <div class="rect red"></div><div class="rect green"></div><div class="rect blue"></div><div class="rect yellow"></div>
, y ¿tiene ese render como divs en la página?
Aquí está el código completo:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
<div class="rect red"></div>
<div class="rect green"></div>
<div class="rect blue"></div>
<div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
var move = arr[ndx];
arr.splice(ndx, 1); //from index #'ndx', remove 1 element
arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}
$(".rect").click( function() { // rearrange the order of divs when one is clicked
var sort = Array.from( $(this).parent().children() );
var current_index = $(this).index();
move_before(sort, current_index); // put each element into a new array
var i = 0;
var updated_arr = [];
while (i <= sort.length) {
updated_arr.push(sort[i]);
i = i+1;
}
document.getElementById("target").innerHTML = updated_arr;
});
</script>
</body>
</html>
3 respuestas
Utilice appendChild()
:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.rect {width:24px; height:12px; border-radius:12px; border:4px solid rgba(0,0,0,0.25); margin-bottom:12px}
.red {background-color:#c21}
.green {background-color:#1c3}
.blue {background-color:#28f}
.yellow {background-color:#ed1}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
<div class="rect red"></div>
<div class="rect green"></div>
<div class="rect blue"></div>
<div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx){ //move the element one place earlier in the array
var move = arr[ndx];
arr.splice(ndx, 1); //from index #'ndx', remove 1 element
arr.splice(ndx-1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}
$(".rect").click( function() { // rearrange the order of divs when one is clicked
var sort = Array.from( $(this).parent().children() );
var current_index = $(this).index();
move_before(sort, current_index); // put each element into a new array
var i = 0;
var updated_arr = [];
while (i <= sort.length) {
updated_arr.push(sort[i]);
i = i+1;
}
for(i=0;i<updated_arr.length-1;i++){
document.getElementById("target").appendChild(updated_arr[i]);
}
});
</script>
</body>
</html>
Esto es similar a:
var div=document.createElement("div");
console.log(div);
document.body.appendChild(div);
Dos cambios menores para que funcione:
- use
<
en lugar de=<
en el bucle para evitar una iteración adicional. - Use
Element.appendChild()
para agregar elementos en un nodo. Puede leer más sobre esto aquí https: //developer.mozilla .org / es-ES / docs / Web / API / Node / appendChild
¡Buen trabajo al usar this
!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<style>
.rect {
width: 24px;
height: 12px;
border-radius: 12px;
border: 4px solid rgba(0, 0, 0, 0.25);
margin-bottom: 12px;
}
.red {
background-color: #c21;
}
.green {
background-color: #1c3;
}
.blue {
background-color: #28f;
}
.yellow {
background-color: #ed1;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<div id="target">
<div class="rect red"></div>
<div class="rect green"></div>
<div class="rect blue"></div>
<div class="rect yellow"></div>
</div>
<script>
function move_before(arr, ndx) {
//move the element one place earlier in the array
var move = arr[ndx];
arr.splice(ndx, 1); //from index #'ndx', remove 1 element
arr.splice(ndx - 1, 0, move); //from the index before #'ndx', remove 0 elements, then insert the value of 'move'
}
$(".rect").click(function() {
// rearrange the order of divs when one is clicked
var sort = Array.from(
$(this)
.parent()
.children()
);
var current_index = $(this).index();
move_before(sort, current_index); // put each element into a new array
var i = 0;
var updated_arr = [];
while (i <= sort.length) {
updated_arr.push(sort[i]);
i = i + 1;
}
updated_arr.map(element =>
document.getElementById("target").appendChild(element)
);
});
</script>
</body>
</html>
No es necesario crear el updated_arr
. Simplemente únase a los outerHTML
de los objetos HTMLElement
en la matriz sort
.
move_before(sort, current_index);
document.getElementById("target").innerHTML = sort.map(elem => elem.outerHTML).join('');
También actualice su evento vinculante a $("#target").bind('click', '.rect', function() { ...... });
Preguntas relacionadas
Preguntas vinculadas
Nuevas preguntas
javascript
Para preguntas sobre la programación en ECMAScript (JavaScript / JS) y sus diversos dialectos / implementaciones (excepto ActionScript). Incluya todas las etiquetas relevantes en su pregunta; por ejemplo, [node.js], [jquery], [json], etc.