skip to Main Content

I’m using Javascript to construct a html, I’m trying to put a label to the right of the checkbox.

I tried different line order with the Javascript code and different appendChild order, but I never get the result I want.

    const div_recordar_login = document.createElement("div");
    div_recordar_login.classList.add("remember-forgot");
    form_login.appendChild(div_recordar_login);

    const label_chk_rec_log = document.createElement("label");
    div_recordar_login.appendChild(label_chk_rec_log);

    const input_chk_rec_log = document.createElement("input");
    input_chk_rec_log.type = "checkbox";
    label_chk_rec_log.textContent = "Recordar usuario ";
    label_chk_rec_log.appendChild(input_chk_rec_log);

This is what I expect in html

    <div class="remember-forgot">
    <label><input type="checkbox">Recordar usuario</label>

This is what I’m getting

    <div class="remember-forgot">
         <label>
         Recordar usuario 
         <input type="checkbox">
         </label>

2

Answers


  1. Chosen as BEST ANSWER

    The solution was to append (not appendChild) a string to the checkbox input.

    const input_chk_rec_log = document.createElement("input")
    input_chk_rec_log.type = "checkbox"
    label_chk_rec_log.appendChild(input_chk_rec_log)
    label_chk_rec_log.append(" Recordar usuario")
    

  2. const div_recordar_login = document.createElement("div");
    div_recordar_login.classList.add("remember-forgot");
    
    form_login.appendChild(div_recordar_login);
    
    const label_chk_rec_log = document.createElement("label");
    div_recordar_login.appendChild(label_chk_rec_log);
    
    const input_chk_rec_log = document.createElement("input");
    input_chk_rec_log.type = "checkbox";
    label_chk_rec_log.appendChild(input_chk_rec_log);
    
    // create a span element for the label text and append it after the checkbox input
    const label_text_span = document.createElement("span");
    label_text_span.textContent = "Recordar usuario";
    label_chk_rec_log.appendChild(label_text_span);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search