[Solved-6 Solutions] Selecting and manipulating CSS pseudo-elements such as ::before and ::after using jQuery - javascript tutorial
Problem:
How to select and manipulate CSS pseudo-elements such as ::before and ::after using jQuery ?
For example, the stylesheet has the following rule:
.span::after{ content:'wiki' }
How to change ‘wiki’ to ‘wikitechy’ using jQuery ?
Solution 1:
You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with javascript.
var addRule = function(sheet, selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
};
addRule(document.styleSheets[0], "body:after", "content: 'wikitechy'");
Solution 2:
We could pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
In HTML:
<span>wiki</span>
In jQuery:
$('span').hover(function(){
$(this).attr('data-content','wikitechy');
});
In CSS:
span:after {
content: attr(data-content) ' any other text we may want';
}
If we need to prevent the 'other text' from showing up, we could combine this with solution like this:
In HTML:
<span>wiki</span>
In jQuery:
$('span').hover(function(){
$(this).addClass('change').attr('data-content','wikitechy');
});
In CSS:
span.change:after {
content: attr(data-content) ' any other text we may want';
}
Read Also
Remove a Particular ElementSolution 3:
To manipulate CSS pseudo elements using the hover() function.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('span').hover(function(){
$(this).addClass('change').attr('data-content','wikitechy');
});
});
</script>
<style>
span.change:after {
content: attr(data-content) ' This is demo text.';
}
</style>
</head>
<body>
<p>Place cursor below...</p>
<span>wiki</span>
</body>
</html>
Solution 4:
We can't select pseudo elements in jQuery because they are not part of DOM. But we can add an specific class to the parent element and control its pseudo elements in CSS.
<script type="text/javascript">
$('span').addClass('change');
</script>
In CSS:
span.change:after { content: 'wikitechy' }
Solution 5:
We can use this:
$('head').append("<style>.span::after{ content:'wikitechy' }</style>");
Solution 6:
Here is the way to access :after and :before style properties, defined in CSS:
// Get the color value of .element:before
var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color');
// Get the content value of .element:before
var content = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('content');