Chapter 01Selection and Node Properties
Given a selection, we can retrieve the number of elements in the selection and the nodes in the selection, and given a node we can retrieve the window owning the node and and style property of the node. Below we discuss the methods in D3.js that allow us to do these things.
Selection.empty and Selection.size
d3.selection type has two methods that allow us determine if a selection is empty and determine how many elements are in the selection. Note that unlike other selection methods, these to methods do not return selection objects.
selection.empty() - returns true if the selection is empty
selection.size() - returns the number of elements in the selection
Selection.node and Selection.nodes
d3.selection type has a pair of methods that allows us to get the Node objects from a selection. They are:
selection.node() - returns the first non-null element in the selection
selection.nodes() - returns an array containing all of the non-null elements in the selection
d3.window(node) returns the window that own’s the node, if it exists.
node is a window,
d3.window returns the window node; if
node is a document,
d3.window returns the document’s default view (i.e. its window); and if
node has a ownerDocument property (i.e. the node descends a document node) the function returns the document’s default view. Otherwise, undefined is returned.
<script> var div1 = d3.select("#div1").node(); var win1 = d3.window(div1.ownerDocument.defaultView); var win2 = d3.window(div1.ownerDocument); var win3 = d3.window(div1); var win4 = d3.window("blah"); console.log(win1); console.log(win2); console.log(win3); console.log(win4); </script> <div id="div1"></div>
d3.style(node, name) is a convenience method for retrieving the value of an node’s
d3. takes 2 arguments, a node and a string, and returns the value of named property in the node’s style property. If the node has an inline style attribute with the given name, its value is returned. Otherwise the computed value is returned. See HTMLElement.style for the difference between inline style values and computed values. `