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?
JavaScript
x
17
17
1
class TestClass extends HTMLElement {
2
constructor() {
3
super();
4
var shadow = this.attachShadow({
5
mode: 'open'
6
});
7
8
var title = document.createElement('h5');
9
title.setAttribute('class', 'whiteText');
10
title.innerText = "Test text"
11
shadow.appendChild(title);
12
}
13
}
14
customElements.define('test-el', TestClass);
15
var container = document.getElementById("container")
16
container.innerHTML = ""
17
container.appendChild(new TestClass());
JavaScript
1
9
1
body {
2
background-color: black;
3
margin: 0;
4
}
5
6
.whiteText {
7
font-family: Helvetica, sans-serif;
8
color: white;
9
}
JavaScript
1
3
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
2
<div id='container'>
3
</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.
JavaScript
1
20
20
1
class TestClass extends HTMLElement {
2
constructor() {
3
super();
4
var shadow = this.attachShadow({
5
mode: 'open'
6
});
7
var title = document.createElement('h5');
8
title.setAttribute('class', 'whiteText');
9
title.innerText = "Test text"
10
shadow.appendChild(title);
11
12
var style = document.createElement('style');
13
style.innerHTML = '.whiteText { font-family: Helvetica, sans-serif; color: white; }';
14
shadow.appendChild(style);
15
}
16
}
17
customElements.define('test-el', TestClass);
18
var container = document.getElementById("container")
19
container.innerHTML = ""
20
container.appendChild(new TestClass());
JavaScript
1
4
1
body {
2
background-color: black;
3
margin: 0;
4
}
JavaScript
1
3
1
<div id='container'>
2
</div>
3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>