JQuery: how to select all elements that are: before or: after pseudo-elements?

in jQuery or basic javascript can I get all the elements with: after or: before the pseudo-element?

I know getcomputedstyle, but this returns all elements with or without: before or: after the pseudo-element.

thanks

EDIT:

Sort of:

$("a:before").each(function () { console.log("element with :before pseudo-element") }); 
+4
source share
3 answers

Nope. The generated content elements are not really part of the DOM. You cannot directly connect to them using JS. They are for presentation only.

You can do something in relation to the actual elements, which may be parents or brothers and sisters, etc. pseudo-elements and modify them that way.

By looking at the BoltClock question linked below, perhaps you can set a common attribute for all pseudo-elements, and then try and select them using jquery based on this attribute.

+1
source

Specify the 'a' tags that you want to select for a class such as 'has-before' and connect to them this way?

0
source

It is possible, but all around!

Check out this demo: http://jsfiddle.net/BE47z/1/

The logic is as follows:

  • List all classes with the definition :before or :after in CSS - this is done by moving the document.styleSheets object (you can change the code only to catch :before or :after , etc.). as needed)
  • Once you get the list of classes, delete the part after: its name in CSS, for example: .a:before becomes .a
  • Now you can get all the elements corresponding to these 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 
0
source

All Articles