Creating custom style content using the <style>
tag with style.innerHTML
can be done like this:
let style = document.createElement("style");
style.setAttribute("id", "raptors");
style.innerHTML =
".puma {" +
"color: purple;" +
"font-size: 50px;" +
"text-align: left;" +
"}";
But what if you want to import styles from a local file like ./styles.css
? You might try something like this:
styles.innerHTML = import `./styles.css`
I attempted a solution using fetch
, but encountered some issues. Is there a better way to do this? Check out my code experiment here:
let style = document.createElement("style");
style.setAttribute("id", "test");
async function loadCss() {
try {
const response = await fetch("./style.css");
const css = await response.text();
style.textContent = css;
} catch (error) {
console.error(error);
}
}
loadCss();