krishna_v
krishna_v

Reputation: 1511

Clear text in svg before adding in d3.js

I would like to clear the text before adding a new value in the svg.

svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

svg.append("text")
      .attr("dy", ".35em")
      .style("text-anchor", "middle")
    .text(function(d) 
    {     
        return months[RAG_input];
    });

The text will change based on the value in the months[RAG_input] array. The months[] contains the months and based on the RAG_input the corresponding array item is displayed.

currently it is overwriting. Is there a way to clear the text before writing.

I have added it in the fiddle http://jsfiddle.net/ThomsonKrish/wjMHE/1/

Upvotes: 0

Views: 1144

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109242

You can check whether the text element exists already before setting the text by selecting it. This way, you can reuse the existing text element.

var text = svg.select("text");
if(text.empty()) {
  text = svg.append("text").attr("dy", ".35em").style("text-anchor", "middle");
}
text.text(function() {
  return months[RAG_input];
});

Upvotes: 1

Related Questions