It is possible but in a round-about way!
Check this demo: http://jsfiddle.net/BE47z/1/
The logic goes like:
- Enumerate all classes that have a
:before
or an :after
definition in CSS - this is done by traversing the document.styleSheets
object (you can change the code to only catch :before
or :after
etc.. as needed)
- Once you get the class list, remove the part after : its name in CSS, for ex:
.a:before
becomes .a
- Now you can get all elements matching those classes
Code
HTML
<div class="element classWithoutBefore">No :before</div>
<div class="element classWithBefore">Has :before</div>
<div class="element class2WithBefore">Has :before</div>
<div class="element class2WithoutBefore">No :before</div>
CSS
.classWithoutBefore {
}
.class2WithoutBefore {
}
.classWithBefore:before {
}
.class2WithBefore:before {
}
.a:before, .b:before {
}
JS
var sheets = document.styleSheets;
var pseudoClasses = [], i = 0, j = 0;
for (i=0; i<sheets.length; i++) {
try {
var rules = sheets[i].cssRules;
for (j=0; j<rules.length; j++) {
if(rules[j].selectorText.indexOf(':before') != -1 || rules[j].selectorText.indexOf(':after') != -1) {
pseudoClasses.push(rules[j].selectorText);
}
}
}
catch(ex) { // will throw security exception for style sheets loaded from external domains
}
}
var classes = [];
if(pseudoClasses.length > 0) {
pseudoClasses = pseudoClasses.join(',').split(','); // quick & dirty way to seperate individual class names
for (i=0; i<pseudoClasses.length; i++) { // remove all class names without a : in it
var colonPos = pseudoClasses[i].indexOf(':');
if(colonPos != -1) {
classes.push(pseudoClasses[i].substring(0, colonPos));
}
}
}
// Elements with the classes in the 'classes' array have a :before or :after defined