Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Targeting pseudo elements with d3 - is it possible?

Tags:

d3.js

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
like image 814
joshua.paling Avatar asked Mar 03 '15 01:03

joshua.paling


People also ask

How do you target pseudo elements?

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.

Can you target pseudo-element in JavaScript?

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.

Can you nest pseudo elements?

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.

What is a d3 selection?

# 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.


1 Answers

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.

like image 169
AmeliaBR Avatar answered Oct 04 '22 21:10

AmeliaBR