【问题标题】:Set the `class` attribute of a dynamically-created element in JavaScript在 JavaScript 中设置动态创建元素的 `class` 属性
【发布时间】:2017-04-25 17:02:14
【问题描述】:

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

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

  this.appendChild(on_off_switch);

 }

但我在查看源代码时注意到on_off_switch 的类未设置为switch demo3

所有其他任务都有效,例如 on_off_switch.style['background-color'] = 'red' 等。

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

【问题讨论】:

    标签: html css custom-element


    【解决方案1】:

    对于historical reasons,使用className 属性而不是class

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 1970-01-01
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多