Why the d is not an object? and how I can access those text objects? (The following code is wrong)
d3.selectAll("svg text").each(function(d, i) {
d.text("New");
});
selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.
append() Function. The selection. append() function is used to append a new element to the HTML tag name as given in the parameters to the end of the element.
style() method to apply style attribute with the specified name and value to the selected elements. The style() method can be used to add styles to the selection. In this example, d3. select("p") selects the <p> element, then the style("color", "red") adds a font-color red to the <p> element.
SVG is text-based, and it is an image format that is vector-based. SVG is the same as the HTML structure. It can be illustrated as the DOM (Document Object Model). The properties of SVG can be described as attributes.
Inside the callback provided to .each()
the parameter d
will refer to the data bound to the element. You should use this
instead which refers to the current element of the iteration. To wrap this into a D3 selection you need to do d3.select(this)
. This will change your snippet to
d3.selectAll("svg text").each(function(d, i) {
d3.select(this).text("New");
});
That said, there is an even more concise and elegant way of achieving the same thing where D3 will do the iteration for you without the need to explicitly call .each()
:
d3.selectAll("svg text").text("New");
To selectivly edit texts which satisfiy some condition, as mentioned in one of your comments, you could use selection.filter()
:
d3.selectAll("svg text")
.filter(function() {
return /^C/.test(d3.select(this).text()); // Check if text begin with a "C"
})
.text("New");
This will preselect all texts starting with a "C" and change the textual content of these texts only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With