Search code examples
htmlcsscustom-element

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


I have a custom element, which is created like:

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

  this.appendChild(on_off_switch);

 }

But I noticed when viewing the source that the on_off_switch's class is not set to switch demo3.

All other assignments work, like on_off_switch.style['background-color'] = 'red', etc.

Is it possible to set the CSS class of a element appended inside a custom element?


Solution

  • For historical reasons, the className property is used instead of class:

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