Santiago García
Santiago García
KPCKevin Powell - Community
Created by Santiago García on 11/9/2023 in #front-end
Setting text of pseudo element from JavaScript
I'm trying to set the text of a pseudo element (::before or ::after) through JavaScript.
h1 {
--text: "Hello World!";
--color: black;
}

h1::before {
content: var(--text);
color: var(--color);
}
h1 {
--text: "Hello World!";
--color: black;
}

h1::before {
content: var(--text);
color: var(--color);
}
Setting the color works as expected:
document.querySelector('h1').style.setProperty('--color', 'hotpink')
document.querySelector('h1').style.setProperty('--color', 'hotpink')
While trying to set the text makes the pseudo element disappear
document.querySelector('h1').style.setProperty('--text', 'Hello World from JS'))
document.querySelector('h1').style.setProperty('--text', 'Hello World from JS'))
js I know there are other ways I can solve this, but I'd like to understand why this does not work. Here is a codesanbox that reproduces the issue: https://codesandbox.io/s/clever-wind-q4r2vh
21 replies