score:35
The most natural way to manipulate just one element is using the filter function:
var data = [[0,0,2],[0,23,5],[2,12,5]];
var circleSet = svg.selectAll()
.data(data)
.enter()
.append('circle');
var filteredCircleSet = circleSet
.filter(function (d, i) { return i === 1;})
// put all your operations on the second element, e.g.
.append('h1').text('foo');
Note that depending on what you do with the other elements you might use one of the two variants of this approach:
variant a): use the filter in the data function (to reduce the data and the appended elements)
variant b): use the filter to exclude instead of to include in order to remove the other elements at the end
See also Filter data in d3 to draw either circle or square
One other way to do it is to use the selection.each method: https://github.com/mbostock/d3/wiki/Selections#wiki-each By using an if statement with the corresponding index you can create a block for one element. E.g.
var data = [[0,0,2],[0,23,5],[2,12,5]];
var circleSet = svg.selectAll()
.data(data)
.enter()
.append('circle')
.each(function (d, i) {
if (i === 1) {
// put all your operations on the second element, e.g.
d3.select(this).append('h1').text(i);
}
});
score:6
Use the preset function i
variable, which references the index of the array object.
var data = [[0,0,2],[0,23,5],[2,12,5]];
circleSet = svg.selectAll()
.data(data)
.enter()
.append('circle')
.attr('fill',function(d,i){i === 1 ? return 'red' : return 'black' };
Find more on array structure references in d3.js at this tutorial
You can also encode each element you append by utilizing the count of the i
index when assigning a class.
var data = [[0,0,2],[0,23,5],[2,12,5]];
circleSet = svg.selectAll()
.data(data)
.enter()
.append('circle')
.attr("class",function(d,i){ return "yourclass item" + i })
var theSecondElement = d3.select(".item1")
Last, you could use the .each method and a conditional to target a specific element
circleSet = svg.selectAll()
.data(data)
.enter()
.append('circle')
.each(function (d, i) {
if (i === 1) {
var that = this;
(function textAdd() {
d3.select(that).append('h1').text(i);
)();
}
});
score:20
In d3 v4 and above, you can use Selection.nodes()
. Assuming i
is the index number you want:
d3.select(someSelection.nodes()[i])
It's a natural one-liner, and it's arguably more readable: you're obviously just getting the node at i
in the order, as a D3 selection.
It looks like it'd be more efficient than the alternatives, which involve looping through the entire selection with .each()
. So, you might think this is O(1), while the other options are O(n).
Unfortunately, Selection.nodes() itself includes an each
loop, so it's also O(n) (not that it's likely to matter in real life unless you call this thousands of times on selections with thousands of nodes):
var nodes = new Array(this.size()), i = -1;
this.each(function() { nodes[++i] = this; });
return nodes;
However, this way you can separate the looping from the getting, which could be useful if efficiency is a major concern.
For example, if you want to loop through each()
in selection A and get the item in the same position from selection B, and you want to avoid loops-within-loops because those selections can be huge and you call this many times, you could structure it like this, which would be O(2n) instead of O(n^2):
var selectionBArray = selectionB.nodes()
selectionA.each(function(d, i) {
var iFromSelectionA = this
var iFromSelectionB = d3.select(selectionBArray[i])
})
...or if you're using arrow functions to preserve this
context:
var selectionBArray = selectionB.nodes()
selectionA.each((d, i, nodes) => {
var iFromSelectionA = d3.select(nodes[i])
var iFromSelectionB = d3.select(selectionBArray[i])
})
You could even (ab)use Selection._groups
, but I wouldn't recommend using a private property like that since it'll break if a D3 update renamed the _groups
property, like this update did.
Source: stackoverflow.com
Related Query
- Get one element from d3js selection, by index
- How to get value from the element using selection in d3
- Get raw element from d3 selection
- D3 remove click events from one element out of a selection
- D3 get attributes from element
- Transition from one forced-directed graph to another graph in d3js
- Get innerHTML from selection
- Get all dom nodes from d3 selection
- Javascript: Array of dictionaries, get all key value pairs from one dictionairy with condition
- Get width from element using D3.js
- How to get web element (id) from the element position in D3.js force graph
- Get the type of element in a selection
- How to create selection from DOM element itself
- D3js : mouseover of one element change opacity of several others elements
- Get click event from SVG bounding box using d3js
- Get max value from JSON objects D3JS
- How do I get the index number from the array in d3?
- Blazor, get Input value from Javascript created DOM Element
- How to get the index of the data element in a histogram on mouseover?
- How can I display tooltips from multiple maps when mousover on one of the maps in D3js
- Get value property of each element in d3 selection
- Exclude an element from a selection
- Get the element attributes from a list in D3
- How can I get the dom svg element from d3 node data?
- How to pass an event from one element to another in d3?
- How to get data from d3js polyline?
- d3.js touch and hold to create a line from one element to another
- d3js get data from multidimensional array
- get class from circle element
- Get group from D3js selectAll in console?
More Query from same tag
- D3 js map overflowing SVG Canvas - Part of the map is completely hidden
- Tooltip behavior on line chart with Date as the x-axis
- "<<" operator in javascript
- Text tag not displaying properly in D3 SVG
- Format labels in D3.js graph
- Keep position of D3 graph after updating data
- Uncaught (in promise) DOMException: The element has no supported sources
- d3 chart - get x axis time of max value
- Find the most recent date and output value by group
- D3 tooltip that is also a a D3 viz
- D3 Force Layout: Fit everything on a page?
- D3 Typescript SVG append not working
- How to bind an angularjs directive to a d3js node defined in a link function
- d3.js - draw stations and path on google map
- Drop-down list's design is crashed with too many elements
- Canvas HTML5 animation with GSAP/d3.js
- Error when transitioning an arc: <path> attribute d: Expected arc flag ('0' or '1')
- D3.js - Creating a rectangle?
- Change the link color of ngx--graph
- Conditional Bar Chart with D3
- How to map an array of objects correctly in Javascript
- d3 geojson changing from one index to the another
- In D3.js, what is the proper way to handle overlapping scatter plot to make it look prettier
- Porting d3.js SVG to HTML5 Canvas?
- Select element with double dot in id, error: "#octo:cat" is not a valid selector
- How to include multiple D3 charts in a Backbone view?
- How to load 30 csv files in parallel using queuejs with d3js?
- Replace svg element with icon
- When integrate elasticsearch with d3.js, "Uncaught TypeError: Cannot read property 'Client' of undefined" I get this error
- make axis of radar chart conditional to existence of value