Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text elements in d3?

Tags:

d3.js

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");
});
like image 835
Iman Avatar asked Jun 30 '16 18:06

Iman


People also ask

What does selectAll do in d3?

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.

How to append HTML in d3?

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.

How to add style in d3 js?

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.

What is use of DOM and SVG in d3?

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.


1 Answers

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.

like image 73
altocumulus Avatar answered Sep 24 '22 23:09

altocumulus