简体   繁体   中英

How to use a div to style radio buttons with javascript

I am trying to make radio buttons appear one under the other, each with their labels. I have used a loop which goes through contents of a json file and creates radio buttons with their labels next to them successfully, but they appear next to each other instead: 在此处输入图像描述

I have attempted to wrap the radio buttons and the labels in a div so that they appear one under the other, but i am not sure how to do it. This is what i have so far:


for (const o of i.options){

        const x = document.createElement("INPUT");
        x.setAttribute("type", "radio");
        x.setAttribute("id", "lord");
        window.data.appendChild(x);


        const y = document.createElement("LABEL");
        const t = document.createTextNode(o);
        y.textContent = "Label text";
        y.setAttribute("for", "lord");
        window.data.appendChild(t);

        const div = document.createElement("div");
        div.style.width = "200px";
        div.style.height = "5px";
        document.getElementById("radioButton1").appendChild(div);
      }

Instead of appending the radio and label to window, append them to the div then append the div to the parent element.

Since div is block level element, it should come vertically

for (const o of i.options) {

  const x = document.createElement("INPUT");
  x.setAttribute("type", "radio");
  x.setAttribute(o.id, "lord"); // if there is id key available 


  const y = document.createElement("LABEL");
  const t = document.createTextNode(o);
  y.appendChild(t); // cheanged here
  y.setAttribute("for", "lord");


  const div = document.createElement("div");
  div.style.width = "200px";
  div.style.height = "5px";
  div.appendChild(x); //changed here
  div.appendChild(y); //changed here
  document.getElementById("radioButton1").appendChild(div);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM