在 JavaScript 中设置动态创建元素的 `class` 属性

Set the `class` attribute of a dynamically-created element in JavaScript

我有一个自定义元素,创建方式如下:

connectedCallback()
{
  var on_off_switch = document.createElement('Div');
  on_off_switch.class = 'switch demo3';

  this.appendChild(on_off_switch);

 }

但是我在查看源代码时注意到 on_off_switch 的 class 没有设置为 switch demo3

所有其他作业都有效,例如 on_off_switch.style['background-color'] = 'red'

是否可以设置附加在自定义元素中的元素的 CSS class

对于historical reasons, the className,使用属性代替class

function connectedCallback () {
  var on_off_switch = document.createElement('div')
  on_off_switch.className = 'switch demo3'

  this.appendChild(on_off_switch)
}

class是元素的名称属性,而className是其对应的属性:

on_off_switch.className = 'switch demo3'
// or    
on_off_switch.setAttribute('class', 'switch demo3')