Introduction
On this article we’ll be displaying the right way to choose and manipulate CSS pseudo-elements, particularly ::earlier than
and ::after
, utilizing JavaScript and jQuery. As an online developer, you have doubtless not less than seen these pseudo-elements in a CSS file, however might not have had the possibility to work together with them programmatically. This text will present you the way and why you would possibly wish to accomplish that.
What are CSS pseudo-elements?
CSS pseudo-elements are key phrases added to selectors that allow you to fashion sure components of a doc. As an example, 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>
component, and the ::after
pseudo-element provides ” – thanks!” after the content material of each <p>
component.
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 leap! Pack my field with 5 dozen liquor jugs.
In the event you have been to test the supply of this web page, you’d see that the “Learn this – ” and ” – thanks!” are usually 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 are usually not truly a part of the DOM, they can not be instantly chosen or manipulated utilizing JavaScript or jQuery. This would possibly seem to be a limitation, however there are workarounds, which we’ll discover within the following sections.
Why would it’s essential manipulate pseudo-elements?
CSS pseudo-elements are a strong device that can be utilized to fashion particular components of your HTML components. They can be utilized so as to add particular results or further content material earlier than or after the content material of a component. Nevertheless, there are occasions whenever you would possibly want to govern these pseudo-elements dynamically, based mostly on consumer interactions or adjustments in your software state. That is the place JavaScript is available in.
As an instance you have got a CSS ::earlier than
pseudo-element that provides an ornamental icon to your buttons. Now, suppose you wish to change this icon when the consumer clicks the button. This modification can’t be achieved with CSS alone. You would wish to make use of JavaScript to pick the pseudo-element after which change it.
Choosing Pseudo-Components utilizing JavaScript
As talked about earlier than, pseudo-elements are usually not a part of the DOM and can’t be instantly 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.
As an instance we’ve a CSS rule for a ::earlier than
pseudo-element on a button:
button::earlier than {
content material: "Click on me";
shade: blue;
}
We are able to 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.fashion.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 fashion
property.
Whereas this methodology works, it isn’t very environment friendly because it requires us to loop by means of all of the cssRules
. In a big app with many stylesheets/guidelines, this doubtless would not carry out effectively. Subsequently, it is really helpful to make use of this methodology sparingly and solely when essential.
Manipulating Pseudo-Components utilizing JavaScript
In JavaScript, manipulating pseudo-elements is a bit tough since they don’t seem to be instantly a part of the Doc Object Mannequin (DOM). Nevertheless, we will nonetheless modify them with a little bit of creativity. We will not instantly choose pseudo-elements in JavaScript, however we will manipulate their types by way of the CSSStyleSheet.insertRule()
methodology.
As an instance we’ve a paragraph with the id “instance” and a ::earlier than
pseudo-element:
<p id="instance">Good day, StackAbuse readers!</p>
#instance::earlier than {
content material: "Greetings! ";
}
Now, suppose we wish 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()
methodology 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 originally 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 truly be taught it!
If it’s essential finally take away this new rule, you are able to do so with doc.styleSheets[0].removeRule()
.
Choosing/Manipulating Pseudo-Components utilizing jQuery
In terms of jQuery, the scenario is analogous. We will not instantly choose pseudo-elements. However we will nonetheless get round this by manipulating the CSS guidelines that apply to them. jQuery does not have a built-in methodology like insertRule()
, however we will use the $('fashion')
selector to append a brand new rule to our stylesheet.
Let’s use the identical HTML and CSS as earlier than:
<p id="instance">Good day, 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:
$('fashion').append("#instance::earlier than { content material: 'Welcome! '; }");
With the append()
methodology, we’re including a brand new rule to the top of our stylesheet. This rule will override the earlier rule for #instance::earlier than
, which leads to the content material being modified.
Alternate options to Manipulating CSS Psuedo-Components
Utilizing Attributes
One other resolution that has been proposed, and presumably a greater one than what we’ve proven above, is to make use of the component’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! ">Good day, StackAbuse readers!</p>
The attr()
methodology selects no matter textual content is given within the data-before
attribute of the component. Utilizing this, you’ll be able to change the textual content within the data-before
attribute, which is able to then alter what the psuedo-elements present.
$('#instance').click on(perform() {
$(this).attr('data-content', 'Welcome! ');
});
Utilizing Courses
One other cheap methodology is to simply use CSS lessons, which can be one thing you are already doing all through your app. You’ll be able to add/take away lessons which have the ::earlier than
or ::after
selectors, thus serving to you manipulate the conduct of the psuedo-elements. It does not give as a lot flexibility because the final choice, however it’s a well-known and easy resolution 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 discovered that whereas pseudo-elements are usually not truly a part of the DOM and cannot be chosen instantly, we will nonetheless manipulate them by dynamically altering the CSS guidelines they’re related to.
Whereas pseudo-elements could be helpful, you could wish to keep away from utilizing them if potential, not less than when it’s essential manipulat their values. They’re not a alternative for semantic HTML components and shouldn’t be used so as to add content material that’s necessary to your web page.