is there any way to dynamically change the text content of the ::after pseudo-element using JS? I am trying to create a form as an exercise (just started learning about web development) and I can't change the text under the password field using JS.
I would like it to tell the user whether the password is too short, or the confirm password field has a different value.
Here are all the files, on github:
https://github.com/mihaib1/sign-up-form
If any more information is needed, I will respond ASAP. Thanks for your help!
Tried using a CSS variable declared in the root, but couldn't make the value of that variable appear on screen and I don't know why. Also, when using CSS variables, they would only change if I used only one word. When trying to set the variable to a string composed of multiple words, it would not change using setProperty.
CodePudding user response:
You can achieve this by using attr()
function in css, and using setAttribute
to change the value of attribute on the dom node:
document.onclick = function() {
document.getElementById("test").setAttribute("data-after", "thank you!")
}
#test::after{
content: attr(data-after);
letter-spacing: 0;
color:red;
}
<div id=test data-after="click me"></div>
CodePudding user response:
By using JS to add your own attribute to your HTML element and calling it in the CSS, Here is the solution
JS
function test() {document.querySelector("#msg").setAttribute("data-text", "My new message")}
HTML & CSS
<style>
#msg {position: relative;}
#msg::after {content: attr(data-text);}
</style>
<span id="msg"></span>
<button onclick='test()'>click</button>