Removing and appending

2,111 views
Skip to first unread message

r34ch

unread,
Aug 9, 2011, 8:25:29 AM8/9/11
to d3...@googlegroups.com
Hey everyone.

I am trying to have line paths draw ontop of other line paths if you mouseover them. I realise if you remove and append that element, it will be drawn last, and therefore 'on top' of the other line paths.

//draw chart lines
var g = vis.selectAll("g.chartLines")
        .data(a_graphInputArray)
      .enter().append("svg:g")
        .attr("class", "chartLines")
.on("mouseover", function() 
{
d3.select(this).select(".chartLine").style("stroke", "42689A") ; 
      });

I am assuming it is the g.container containing the path I want to remove and append? I tried

d3.select(this).select(".chartLine").remove().append("svg:g").style("stroke", "42689A") ;

This removes the element, but does not append it again. What am I doing wrong?

Cheers

Kevin Lynagh

unread,
Aug 9, 2011, 9:54:05 AM8/9/11
to d3-js
I usually take advantage of the fact that the standard DOM's
#appendChild method will move a node if you give it something that is
already in the document.
You could say

.on("mouseover", function(){ this.parentNode.appendChild(this); })

which would move the moused over element to the end of its parent
element.
Note that #parentNode and #appendChild are standard DOM methods, not
d3 methods.

r34ch

unread,
Aug 9, 2011, 11:12:44 AM8/9/11
to d3...@googlegroups.com
That's even better than what I wanted, works perfectly, avoids a tons of problems I encountered, thanks.

Mike Bostock

unread,
Aug 9, 2011, 12:43:36 PM8/9/11
to d3...@googlegroups.com
> .on("mouseover", function(){ this.parentNode.appendChild(this); })

+1 This is why the `this` context is a native DOM element rather than
a single element selection. If you're manipulating a single element,
it's perfectly reasonable to use the raw W3C DOM API. It's possible
that we could extend D3's `append` operator to append existing
elements rather than create them, but that could be a bit tricky to
fit into the data-driven design. Using the DOM API is the way to go in
this case.

Mike

Reply all
Reply to author
Forward
0 new messages