将样式应用于动态创建的复选框

Apply styling to dynamically created checkbox

我从 bootstrap 那里得到了一组复选框,它们看起来更像是按钮而不是复选框,但它们的选中状态仍然会在点击时切换。我在表单上有一个文本输入,允许用户添加带有与用户输入对应的标签和值的复选框。所有复选框都在同一个 div 组件中。

我使用 javascript 动态创建新复选框并将其附加到 label,后者附加到包含复选框的 div。新的复选框出现在页面上,但没有样式,链接在 html 文档的头部。如何将样式应用于新复选框?

这是我正在使用的javascript:

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

两个答案都正确:

element.className = "new-class"

只会将此元素 class 名称设置为“new-class” 同时:

element.classList.add("new-class")

将为现有的 class 集添加一个新的 class。如果您要在新创建的复选框中进一步扩展 classes,此功能可能会很有用。

This fiddle 显示差异。

  1. .className ref
  2. .classList ref