Skip to content
Advertisement

How do you apply a class’s style with setAttribute inside a class that extends HTMLElement?

I have a class that I add an element with a class name that should make the text white which I have defined in my CSS’s style, but it does not. The text remains black. How am I supposed to achieve this other than setting the element’s CSS manually?

class TestClass extends HTMLElement {
  constructor() {
    super();
    var shadow = this.attachShadow({
      mode: 'open'
    });

    var title = document.createElement('h5');
    title.setAttribute('class', 'whiteText');
    title.innerText = "Test text"
    shadow.appendChild(title);
  }
}
customElements.define('test-el', TestClass);
var container = document.getElementById("container")
container.innerHTML = ""
container.appendChild(new TestClass());
body {
  background-color: black;
  margin: 0;
}

.whiteText {
  font-family: Helvetica, sans-serif;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id='container'>
</div>

Advertisement

Answer

You have added h5 element to the shadow dom so the style is not applied.

To apply the style, it is needed to define independent <style> tag inside shadow dom as follows.

class TestClass extends HTMLElement {
  constructor() {
    super();
    var shadow = this.attachShadow({
      mode: 'open'
    });
    var title = document.createElement('h5');
    title.setAttribute('class', 'whiteText');
    title.innerText = "Test text"
    shadow.appendChild(title);
    
    var style = document.createElement('style');
    style.innerHTML = '.whiteText { font-family: Helvetica, sans-serif; color: white; }';
    shadow.appendChild(style);
  }
}
customElements.define('test-el', TestClass);
var container = document.getElementById("container")
container.innerHTML = ""
container.appendChild(new TestClass());
body {
  background-color: black;
  margin: 0;
}
<div id='container'>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement