stumpylumpy stumpylumpy - 7 days ago 6
HTML Question

How to add a line break after each dynamically created checkbox?

Here's the code for the dynamically created checkboxes. How do I add line breaks to the code so that I have one checkbox per line? I tried to do

document.createElement("br")
and appending it after
get.appendChild(label)
but it didn't work.

function setCheckboxes(browser) {
var get = document.getElementById("get");

if (browser == "courses") {
for (var i = 1; i < coursesGetKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = coursesGetKeys[i];
checkBox.name = "r";
label.textContent = setOpt(coursesGetKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}

if (browser == "rooms") {
for (var i = 1; i < validRoomsKeys.length; i++) {
var checkBox = document.createElement("input");
var label = document.createElement("label");
checkBox.type = "checkbox";
checkBox.value = validRoomsKeys[i];
checkBox.name = "r";
label.textContent = setOpt(validRoomsKeys[i], browser);
get.appendChild(checkBox);
get.appendChild(label);
//label.appendChild(document.createTextNode(setOpt(validCoursesKeys[i], dataset)));
}
}
};

Answer

You already know how to create an input:

var checkBox = document.createElement("input");

and how to append it:

get.appendChild(checkBox); // get is the parent element you selected at the top of your code

So your first hunch was correct, you can also do this:

var br = document.createElement("br");
get.appendChild(br);

which creates a br element, and then also appends it to the "get" parent.

Comments