Home > Net >  Javascript only changing every second element in loop
Javascript only changing every second element in loop

Time:09-21

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>

CodePudding user response:

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")
        )
    );
});
  • Related