Introduction
On this article we’ll be displaying easy methods to choose and manipulate CSS pseudo-elements, particularly ::earlier than
and ::after
, utilizing JavaScript and jQuery. As an internet developer, you have doubtless a minimum of seen these pseudo-elements in a CSS file, however could not have had the prospect to work together with them programmatically. This text will present you ways and why you would possibly need to achieve this.
What are CSS pseudo-elements?
CSS pseudo-elements are key phrases added to selectors that allow you to model sure elements of a doc. As an illustration, the ::earlier than
and ::after
pseudo-elements are used to insert content material earlier than or after the content material of a component.
p::earlier than {
content material: "Learn this - ";
}
p::after {
content material: " - thanks!";
}
Within the above code, the ::earlier than
pseudo-element provides “Learn this – ” earlier than the content material of each <p>
aspect, and the ::after
pseudo-element provides ” – thanks!” after the content material of each <p>
aspect.
That is what it could truly seem like:
The short brown fox jumps over the lazy canine. Waltz, dangerous nymph, for fast jigs vex. Sphinx of black quartz, decide my vow. How vexingly fast daft zebras soar! Pack my field with 5 dozen liquor jugs.
Should you have been to verify the supply of this web page, you’d see that the “Learn this – ” and ” – thanks!” should not truly within the <p>
tag, they’re inserted by the CSS.
Notice: The ::earlier than
and ::after
pseudo-elements are sometimes used with the content material
property, which is used to insert generated content material.
Since these pseudo-elements should not truly a part of the DOM, they can not be immediately chosen or manipulated utilizing JavaScript or jQuery. This would possibly appear to be a limitation, however there are workarounds, which we’ll discover within the following sections.
Why would it’s good to manipulate pseudo-elements?
CSS pseudo-elements are a robust software that can be utilized to model particular elements of your HTML parts. They can be utilized so as to add particular results or additional content material earlier than or after the content material of a component. Nevertheless, there are occasions whenever you would possibly want to control these pseudo-elements dynamically, based mostly on consumer interactions or adjustments in your software state. That is the place JavaScript is available in.
For instance you might have a CSS ::earlier than
pseudo-element that provides an ornamental icon to your buttons. Now, suppose you need to change this icon when the consumer clicks the button. This transformation can’t be achieved with CSS alone. You would wish to make use of JavaScript to pick the pseudo-element after which change it.
Deciding on Pseudo-Components utilizing JavaScript
As talked about earlier than, pseudo-elements should not a part of the DOM and can’t be immediately chosen utilizing JavaScript. Nevertheless, we will nonetheless manipulate them by altering their related CSS guidelines. To take action, we have to first choose the CSS rule that defines the pseudo-element.
For instance we’ve a CSS rule for a ::earlier than
pseudo-element on a button:
button::earlier than {
content material: "Click on me";
coloration: blue;
}
We will choose this rule utilizing JavaScript’s doc.styleSheets
and cssRules
properties. Here is how:
let styleSheet = doc.styleSheets[0];
let cssRule;
for (let rule of styleSheet.cssRules) {
if (rule.selectorText === 'button::earlier than') {
cssRule = rule;
break;
}
}
console.log(cssRule.model.content material);
Within the above code, we first choose the primary stylesheet of the doc. Then, we iterate over its cssRules to seek out the rule with the selector ‘button::earlier than’. As soon as we discover the rule, we will entry its types utilizing the model
property.
Whereas this technique works, it is not very environment friendly because it requires us to loop by way of all of the cssRules
. In a big app with many stylesheets/guidelines, this doubtless would not carry out nicely. Subsequently, it is beneficial to make use of this technique sparingly and solely when obligatory.
Manipulating Pseudo-Components utilizing JavaScript
In JavaScript, manipulating pseudo-elements is a bit difficult since they aren’t immediately a part of the Doc Object Mannequin (DOM). Nevertheless, we will nonetheless modify them with a little bit of creativity. We won’t immediately choose pseudo-elements in JavaScript, however we will manipulate their types by way of the CSSStyleSheet.insertRule()
technique.
For instance we’ve a paragraph with the id “instance” and a ::earlier than
pseudo-element:
<p id="instance">Hiya, StackAbuse readers!</p>
#instance::earlier than {
content material: "Greetings! ";
}
Now, suppose we need to change the content material of the ::earlier than
pseudo-element to “Welcome! ” utilizing JavaScript. Here is how we will do it:
doc.styleSheets[0].insertRule("#instance::earlier than { content material: 'Welcome! '; }", 0);
Right here, styleSheets[0]
refers back to the first stylesheet linked/embedded within the HTML doc. The insertRule()
technique takes two parameters: the CSS rule to be inserted, and the index at which to insert the rule. On this case, we’re inserting our rule at the start of the stylesheet (index 0).
Take a look at our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and really be taught it!
If it’s good to ultimately take away this new rule, you are able to do so with doc.styleSheets[0].removeRule()
.
Deciding on/Manipulating Pseudo-Components utilizing jQuery
In terms of jQuery, the scenario is comparable. We won’t immediately choose pseudo-elements. However we will nonetheless get round this by manipulating the CSS guidelines that apply to them. jQuery would not have a built-in technique like insertRule()
, however we will use the $('model')
selector to append a brand new rule to our stylesheet.
Let’s use the identical HTML and CSS as earlier than:
<p id="instance">Hiya, StackAbuse readers!</p>
#instance::earlier than {
content material: "Greetings! ";
}
Now, let’s change the content material of the ::earlier than
pseudo-element to “Welcome! ” utilizing jQuery:
$('model').append("#instance::earlier than { content material: 'Welcome! '; }");
With the append()
technique, we’re including a brand new rule to the tip of our stylesheet. This rule will override the earlier rule for #instance::earlier than
, which ends up in the content material being modified.
Alternate options to Manipulating CSS Psuedo-Components
Utilizing Attributes
One other answer that has been proposed, and probably a greater one than what we’ve proven above, is to make use of the aspect’s attribute to specify earlier than/after content material. For instance:
#instance::earlier than {
content material: attr(data-before);
}
<p id="instance" data-before="Greetings! ">Hiya, StackAbuse readers!</p>
The attr()
technique selects no matter textual content is given within the data-before
attribute of the aspect. Utilizing this, you possibly can change the textual content within the data-before
attribute, which can then alter what the psuedo-elements present.
$('#instance').click on(perform() {
$(this).attr('data-content', 'Welcome! ');
});
Utilizing Lessons
One other affordable technique is to only use CSS lessons, which can be one thing you are already doing all through your app. You possibly can add/take away lessons which have the ::earlier than
or ::after
selectors, thus serving to you manipulate the conduct of the psuedo-elements. It would not give as a lot flexibility because the final choice, but it surely’s a well-known and easy answer to a troublesome drawback.
Conclusion
On this article, we took a have a look at CSS pseudo-elements and the way we will work together with them utilizing JavaScript and jQuery. We have realized that whereas pseudo-elements should not truly a part of the DOM and cannot be chosen immediately, we will nonetheless manipulate them by dynamically altering the CSS guidelines they’re related to.
Whereas pseudo-elements may be helpful, you might need to keep away from utilizing them if doable, a minimum of when it’s good to manipulat their values. They’re not a substitute for semantic HTML parts and shouldn’t be used so as to add content material that’s vital to your web page.