I am using web components. I have the following html structure
<div class="test">
#shadow-root (open)
<overlay-trigger type="modal">
<div id = "login-dialog">
#shadow-root (open)
<div id = "modal">
I have the following code
const styleString = String(styles);
const style = document.createElement("style");
style.type = "text/css";
style.innerHTML = styleString;
const styleString2 = String(guestModalStyles);
const style2 = document.createElement("style");
style2.type = "text/css";
style2.innerHTML = styleString2;
let host = this.renderRoot?.querySelector('overlay-trigger[type="modal"]')?.querySelector("#login-dialog")?.shadowRoot?.querySelector(".modal");
if (host) {
host?.appendChild(style);
host?.appendChild(style2);
}
How can I add styles to the modal element? The one with class = "modal"? I’m I doing it right above?
3
Answers
Your code looks for the most part right, however there are several changes expected to guarantee the styles are applied to the right component inside the Shadow DOM.
Rather than utilizing this.renderRoot, utilize the shadowRoot property straightforwardly. On the off chance that you are utilizing the this.attachShadow() technique to make the Shadow DOM, this.shadowRoot will provide you with the base of the Shadow DOM.
While utilizing querySelector inside the Shadow DOM, you want to utilize the ::shadow or ::opened pseudo-components to choose components inside the Shadow DOM.
Here is the changed code:
An easier way just to know you are doing this correctly is to add a css path getter function (as demonstrated here: Get CSS path from Dom element) to your code temporarily (use console.log or alert) then remove the code but save the selector.
Once you have an
Element
object, styling it is as easy asyou can use
document.styleSheets
property for accessing your CSS pages(it returns an array, iterate over array to access specific CSS stylesheet) which are linked to your html page and use csspagefromstyleSheet.insertRule()
method to add styles to your CSS.