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 ?
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'");
Copy Code
We could pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
In HTML :
In jQuery:
$('span').hover(function(){
$(this).attr('data-content','wikitechy');
});
Copy Code
In CSS:
span:after {
content: attr(data-content) ' any other text we may want';
}
Copy Code If we need to prevent the 'other text' from showing up, we could combine this with solution like this:
In HTML:
In jQuery:
$('span').hover(function(){
$(this).addClass('change').attr('data-content','wikitechy');
});
Copy Code In CSS:
span.change:after {
content: attr(data-content) ' any other text we may want';
}
Copy Code
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>
Copy Code 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>
Copy Code
In CSS:
span.change:after { content: 'wikitechy' }
Copy Code
We can use this:
$('head').append("<style>.span::after{ content:'wikitechy' }</style>");
Copy Code
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');
Copy Code