7

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
joshua.paling
  • 13,762
  • 4
  • 45
  • 60

1 Answers1

8

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.

Community
  • 1
  • 1
AmeliaBR
  • 27,344
  • 6
  • 86
  • 119