score:16

Accepted answer

You have a few options to select a specific element you want to remove. If that element is identified by a class, you can do

d3.select("path.line").remove();

If you want to remove all lines on the graph, you should use

d3.selectAll("path.line").remove();

If, as in your example, there are several of these elements, you can assign an ID to them and use that to remove it.

svg.append("path")
// ...
.attr("id", "id");

// ...

d3.select("#id").remove();

score:2

You can store the line in a variable and then use that as a handle to remove it later.

In d3, the .append operator returns the appended child, so to do this, all you need to do is this:

var myLine;

function(appendLine){
    ...
    myLine = svg.append("path").datum(data)...
    ...
}

function(removeLine){
    myLine.remove()
}

Use appendLine when you want to create the line and removeLine to remove it. With this method, you can have a variable for each line you want to control, or else use variable scoping to not have to worry about it. It depends on what the rest of your code looks like.

Alternately, if you have a line with an ID that you want to remove, d3.select('#myId').remove() should work.


Related Query

More Query from same tag