D3 selectAll multiple classes AND or OR
Asked Answered
P

2

11

I am trying to select two classes like this,

d3.selectAll(".class1.class2")

but this appears to select an element with both class1 AND class2. How do I select an element by class with class1 OR class2 but the classes need not be mutually exclusive, so an element with both classes should also get selected.

Perhaps the solution is just,

 d3.selectAll(".class1")
 .........;
 d3.selectAll(".class2")
 .........;
Photic answered 10/8, 2017 at 14:30 Comment(0)
J
21

As per D3's documentation the selection methods accept W3C selector strings. If you follow this link and dig into this API you end up at section 4.1 Selector Lists of the Selectors Level 4 Draft which specifies:

A comma-separated list of selectors represents the union of all elements selected by each of the individual selectors in the selector list.

For your example this means the correct selector string would be ".class1,.class2". Have a look at the following snippet which uses this selector string to color all paragraphs having either one or both of the classes class1 or class2.

d3.selectAll(".class1,.class2")
  .style("color", "red");
<script src="https://d3js.org/d3.v4.js"></script>

<p class="class1">class1</p>
<p class="class2">class2</p>
<p class="class3">class3</p>
<p class="class1 class2">class1 class2</p>
Jerrodjerrol answered 10/8, 2017 at 15:21 Comment(0)
P
1

This seems to work,

d3.selectAll(".bar||.xAxisText")
Photic answered 10/8, 2017 at 14:35 Comment(1)
It works, but it throws a warning DOMException: Failed to execute 'querySelectorAll' on 'Element': '.class1||.class2||.class3' is not a valid selector.Nahshon

© 2022 - 2024 — McMap. All rights reserved.