Reputation: 685
Is it possible to select an element in contained DOM tree using d3.js?
For example, I have the following code:
html:
<div id="drawRegion">
<div id="iWantToSelectThis">
</div>
</div>
<div id="iWantToSelectThis">
</div>
<script src="https://d3js.org/d3.v5.min.js"></script>
js:
const drawRegion= d3.select("#drawRegion");
Now in js I want to select the div with id="iWantToSelectThis"
which is inside the div with id="drawRegion"
. I hope to do so using the element I got here: const drawRegion= d3.select("#drawRegion");
.
And if I will do just d3.select("#drawRegion");
I will get two divs.
Upvotes: 0
Views: 202
Reputation: 2886
Id's must be unique, and d3.select will return only the first matching element from the DOM.
d3.select selects the first matching element whilst d3.selectAll selects all matching elements. Each function takes a single argument which specifies the selector string.
So, add a class to your elements :
<div id="drawRegion">
<div class="iWantToSelectThis" id="toSelect_1">
</div>
</div>
<div class="iWantToSelectThis" id="toSelect_2"></div>
then if you want to select only the first element :
d3.select('#toSelect_1');
and if you want to select both :
d3.selectAll('.iWantToSelectThis');
Upvotes: 2
Reputation: 22
You can do it in one of two ways you can either create a more specific selector or select first drawRegion
as you said and then select iWantToSelectThis
from there.
Option 1:
let element = d3.select('#drawRegion>#iWantToSelectThis');
Option 2:
let drawRegion = d3.select('#drawRegion');
let element = drawRegion.select('#iWantToSelectThis');
Here is an example on how to do it: https://jsfiddle.net/5189rxfa/5/
Upvotes: -1