Reputation: 5
I have a collection of checkboxes which I got from bootstrap that appear more as buttons than checkboxes, but their checked status still toggles on clicks. I have a text input on the form that allows the user to add checkboxes with labels and values corresponding to the user input. All of the checkboxes are in the same div
component.
I use javascript to dynamically create the new checkbox and append it to a label
, which gets appended to the div
containing the checkboxes. The new checkbox appears on the page, but without the styling, which is linked in the head of the html document. How can I apply the styling to the new checkbox?
Here is the javascript that I am using:
function addRestriction() {
let userInput = document.getElementById("add_other").value; // get user input
let newBox = document.createElement("input");
newBox.type = "checkbox";
newBox.autocomplete = 'off';
newBox.name = 'diet_button';
newBox.value = userInput;
let newLabel = document.createElement("label");
newLabel.class = "btn btn-outline-secondary active";
newLabel.appendChild(newBox);
newLabel.appendChild(document.createTextNode(userInput));
document.getElementById('diet_restrictions').appendChild(newLabel);
document.getElementById('add_other').value = '';
}
Upvotes: 0
Views: 579
Reputation: 160
Both answers are correct:
element.className = "new-class"
Will set this elements only class name to "new-class" While:
element.classList.add("new-class")
Will add a new class to already existing set of classes. This feature might be useful in case you are going to further expand classes in your newly created checkboxes.
This fiddle shows the differences.
Upvotes: 1