This works just fine:
d3.selectAll('ul li')
.style('background', 'red');
However, this doesn't do anything:
d3.selectAll('ul li:before')
.style('background', 'red');
The selection returned by d3.selectAll('ul li:before')
is empty, even though the :before
elements do exist, and have some existing CSS styling.
Is it possible to target pseudo elements with d3?
And if it is, a quick follow up question: How would I target all the :before
pseudo-elements directly on (ie, not within) a particular selection?
Eg:
var listItems = d3.selectAll('ul li');
var beforeElements = listItems.selectAll('&:before'); // SASS-style selector obviously won't work here
You can use the :target pseudo-class to create a lightbox without using any JavaScript. This technique relies on the ability of anchor links to point to elements that are initially hidden on the page. Once targeted, the CSS changes their display so that they are shown.
When you inspect your page, you found them written without the tag convention like <pseudo-element> but like that ::pseudo-element. That is because they are defined in the CSSOM of your browser and does not exist in the DOM and that's why it's impossible to target it in javascript.
The W3C Recommendation is quite clearly against nesting pseudo-elements: Only one pseudo-element may appear per selector, and if present it must appear after the sequence of simple selectors that represents the subjects of the selector.
# d3.select(selector) · Source. Selects the first element that matches the specified selector string. If no elements match the selector, returns an empty selection. If multiple elements match the selector, only the first matching element (in document order) will be selected.
It is not possible the way you're trying to do it.
The querySelector methods, on which D3's select functions are based, never return results for pseudo-element selectors.
Furthermore, the D3 style
method works by setting inline style attributes on the selected elements. You cannot set inline styles for pseudo-elements, so setting the style attribute on the parent element won't work either.
What you could do is select the parent elements, give them a class name, and then use CSS stylesheet rules to target the :before
/:after
pseudo-elements for objects of that class. If you would need to dynamically create the CSS rules, see this Q&A.
However, it is probably easiest to just create empty <span>
or <div>
child elements, and style those instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With