score:1

Unless you want to deal with <defs> and gradients, you cannot set two or more fill attributes to the same <text>.

The easiest solution is breaking that text of yours and appending a <tspan> with another style. How to break the text is a problem that depends on your exact goal, which you didn't specify in the question. In the following demo, I'm using a hyphen to break the texts.

Here it is:

var svg = d3.select("svg");
var data = ["This is some text - with different colours",
  "This is another text - with different colours",
  "This is the last text - and the colours are still different"
];

var text = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d, i) {
    return 40 + i * 40
  })
  .text(function(d) {
    return d.split("-")[0]
  })
  .append("tspan")
  .style("fill", "red")
  .text(function(d) {
    return d.split("-")[1]
  })
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>


Related Query

More Query from same tag