How to add a pseudo-element in jquery

$('.email').blur(function() {
if (!validateEmail($(this).val()) ) {
$(this).removeClass("blur").addClass("focus");
} else {
$(this).removeClass("focus").addClass("blur");
}
})
    <input type="email" size="61" class="email"></input>
.focus{border: 1px solid red;outline: none;}
.blur{border: 1px solid #7dc855;outline: none; }

.focus:after{
content: "\00D7";
position: relative;
top: -24px;
left: 500px;
color: red;
}

.blur + label:before{
content: "\2713";
position: relative;
top: -24px;
left: 500px;
color: #7dc855;
}

When my email doesn’t validate I want to add the red border from the class focus and an X mark from the pseudo-element before. The code shows the red border but it doesn’t show the X mark. How do I add the pseudo-element to my text box?

You could just use the invalid pseudo class:-

input[type=email]:invalid {border: 1px solid red;outline: none;}

The :before pseudo-class adds some content into the element, before any other children. Input elements don’t have children though – and they don’t actually have a closing tag. If you want to add an X with a pseudo class, you’ll have to add it to a sibling like you’ve done it with the label.

1 Like

\00D7 is the X mark.

As @m3g4p0p points out, you are trying to add content to what should be a self closing element, one that does not hold content.
You have:-

<input type="email" size="61" class="email"></input>

This is invalid, there is no closing tag, and therefore no content:-

<input type="email" size="61" class="email">

So you would have to put an “X” maybe next to the input or label. Though the red border and label may be enough.

Again, this is another example of over complication by unnecessary use of js to do something that css alone can already do.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.