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")
.........;
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>
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