Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Javascript only changing every second element in loop

I have written the following code, which should replace a value evaluating to either 0 or 1 inside the for-loop. But it only changes every second element in the table to correspondent switch element. What am I doing wrong here? I tried the code with $("td[headers='blub']").eq(i).text("false") \.text("true") and it changed every value correctly... so it has something to do with the appendchild... I also tried to remove the child after every iteration but not worked properly

var length = $("td[headers='blub']").text().length;

for (var i = 0; i <= length; i++) {
  if ($("td[headers='blub']").eq(i).text() == 1) {
    let la = document.createElement("LABEL");
    la.className = "switch";
    let x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    let sp = document.createElement("SPAN");
    sp.className = "slider round";

    x.checked = true;
    la.appendChild(x);
    la.appendChild(sp);

    $("td[headers='blub']").eq(i).replaceWith(la);
  } else {
    let la = document.createElement("LABEL");
    la.className = "switch";
    let x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    let sp = document.createElement("SPAN");
    sp.className = "slider round";

    x.checked = false;
    la.appendChild(x);
    la.appendChild(sp);

    $("td[headers='blub']").eq(i).replaceWith(la);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There are multiple issues:

  • The length variable is set to the length of a string, not to the number of matching DOM elements.
  • A for loop should go to < length, not <= length
  • The effect you describe is the consequence of replacing td elements with something else, and so you reduce the number of matches with $("td[headers='blub']") making .eq(i) skip the next element that you expected to get.
  • Replacing td elements with other types of elements will lead to invalid HTML. You should keep the td elements and change their content instead.
  • You mix jQuery with non-jQuery methods. If you use jQuery, go all the way.

Here is what I would suggest:

$("td[headers='blub']").each(function () {
    let checked = $(this).text().trim() == "1";
    $(this).text("").append(
        $("<label>").addClass("switch").append(
            $("<input>", { type: "checkbox", checked }),
            $("<span>").addClass("slider round")
        )
    );
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda