Skip to content Skip to sidebar Skip to footer

Identify Given Array Is A D3 Selection

How do I identify that the given array is a d3 selection. I have tried this function Chart(container, data) { var isd3Selection = container instanceof Array && typeof c

Solution 1:

V4 way to do this:

As per the documentation

d3.selection()

Selects the root element, document.documentElement. This function can also be used to test for selections (instanceof d3.selection) or to extend the selection prototype. For example, to add a method to check checkboxes:

You can test it like this:

d3.select(document.body) instanceof d3.selection// true

Solution 2:

Depending on your version of D3 you might use one of the following:

v3

As laid out in my answer to "d3.selection type check in IE" this requires a little workaround. Because d3.selection is provided as a means to extend the selection's functionality you could add a new property to d3.selection which will be made accessible by any selection, wether by prototyping or by copying properties.

// Include this at the start of your script to include the// property in any selection created afterwards.
d3.selection.prototype.isD3Selection = true;

d3.select(document.body).isD3Selection;   // true 

v4

As of v4 a selection is not just a nested array any more but a JavaScript object, which will make life even more simple. You can use the standard constructor property to check for a D3 selection:

d3.select(document.body).constructor.name === "Selection"// true

Note, that this will only work when using the unminified version of D3 as pointed out by O. R. Mapper in their comment. For v4 the preferred solution should be using the instanceof operator as was laid out in thedude's answer.

Post a Comment for "Identify Given Array Is A D3 Selection"