Equivalent method of ".getComputedTextLength()" in d3.js
Solution 1
D3 selections are, in fact, objects (since D3 v4.0). However, there is no method for computing the length of the text in an object because the object itself has no presence in the DOM and, therefore, has no length. You can only compute the length (in pixels) of a DOM element.
That being said, you can use getComputedTextLength()
with a D3 selection, if you use that selection to point to the SVG element. For instance, using node()
:
d3.select("foo");//this is a D3 selection
d3.select("foo").node();//this is the DOM element
Here is a demo:
var svg = d3.select("svg");
var text = svg.append("text")
.attr("x", 10)
.attr("y", 30)
.text("Hello world!");
console.log("the text has " + d3.select("text").node().getComputedTextLength() + " px")
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Solution 2
Simply access the DOM elements inside selection operations with this
to benefit from bulk node processing customary with D3
, e.g.
d3.selectAll('tspan.myClass')
.each(function(d) {
console.log(this.getComputedTextLength());
});
or
d3.selectAll('tspan.myClass')
.attr('transform', function(d) {
var width = this.getComputedTextLength() + 2 * padding;
return 'translate(' + width / 2 + ' 0)');
});
this
is bound to the current DOM node.
selection.node()
only returns the first element in the selection.
As of D3
4.* there's also selection.nodes()
which recovers all DOM nodes in a selection, so you can do
d3.selectAll('tspan.myClass').nodes().forEach(function(el) {
console.log(el.getComputedTextLength());
});
though its use is less idiomatic than grabbing the element via this
inside selection.attr
, selection.style
, selection.filter
, selection.each
etc. as in the snippets above it.
ozil
Skill set HTML Javascript D3.js JQuery css AngularJS Node.JS C C++ Java C# SQL
Updated on June 21, 2022Comments
-
ozil almost 2 years
What is the equivalent of
.getComputedTextLength()
method ind3
..getComputedTextLength()
works onDom
element notd3
element's object.
Edit (Image added)
-
ozil about 7 years
d3.select("foo").node();
is still returningd3
object (not DOM element). I am working in salesforce -
David R. about 6 yearsThere is not need to to do a
.select()
since you already have the d3 object intext
, sotext.node().getComputedTextLength()
is all you need.