简体   繁体   中英

Apply styling to dynamically created checkbox

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 = '';
            }

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.

  1. .className ref
  2. .classList ref

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