I have a selection of elements that I’m trying to filter down based on a particular style value (I want just the ones with opacity=1). I’m looking at the documentation for selection.filter along with selection.select and selection.selectAll as well but I’m confused about the correct usage with a function argument.
“select” indicates that it selects the first matching element (as expected) but then the example in the filter documentation shows it being used with a function to select the “odd” elements while maintaining the index.
“selectAll” indicates that you can return an array of elements, but that the function argument is invoked one-by-one in the usual way for each element in the original selection. I’m having difficulty imagining a use case for this.
I guess what I’m wondering is whether there are any tutorials or examples around that discuss the correct usage of these functions?
Thanks,
scott
If you want to reduce a selection to a subset of selected elements, use filter. If you want to select descendent elements, use select or selectAll.
Most often, filter is used to filter elements based on data or index. However, you can access the selected element as
thiswithin the filter function. Thus, if you have some elements selected, and you want to reduce that selection to only those elements with an opacity of 1, you can say:To be safe, you might prefer to look at the computed style rather than the element’s style properties. This way, if the opacity is inherited from a stylesheet, you’ll get the correct value; otherwise, when a style is inherited
this.style.opacitywill be the empty string.Or equivalently, select the node and use selection.style:
You might find it easier if you filter by data or by class, instead of by computed style property. For example, if you set a class on your nodes, you can filter a selection by class instead: