score:0

Accepted answer

To get the text content of the SVG element directly you can use textContent or innerHTML in modern browsers. For instance:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    console.log(this.textContent)
  })
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

However, because you're using a D3 selection, not an SVG node, you should use text as a getter, which is text(). By the way, text() internally uses textContent:

export default function(value) {
  return arguments.length
      ? this.each(value == null
          ? textRemove : (typeof value === "function"
          ? textFunction
          : textConstant)(value))
      : this.node().textContent;
}

Finally, you don't need that if block. To toggle between 0 and 1, just do:

this.textContent = 1 - (+this.textContent);

You can even drop the unary plus, since the string will be converted to a number anyway:

this.textContent = 1 - this.textContent;

Here is the snippet:

var svg = d3.select("svg")
var txt1 = svg.append("text")
  .text("0")
  .attr("x", 10)
  .attr("y", 20)
  .on("click", function() {
    this.textContent = 1 - (+this.textContent);
  })
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>


Related Query