2

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

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
mihaib1
  • 33
  • 3
  • If you plan on editing the content, it seems like having an element placed after the fields would be the easiest to manage. – imvain2 Dec 27 '22 at 19:52

2 Answers2

5

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>
a user
  • 23,300
  • 6
  • 58
  • 90
1

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>