Skip to content

How to access the parentNode of a selection to raise an element?

I’ve created the following document:

    <path class=​"line" name=​"gene_1" stroke=​"#aec7e8" d=​"M10.47...">​</path>​
    <path class=​"line" name=​"gene_2" stroke=​"#aec7e8" d=​"M10.47...">​</path>​
    <path class=​"line" name=​"gene_3" stroke=​"#aec7e8" d=​"M10.47...">​</path>​

When I mouse over each path I want to append it last inside the svg:g so it appears on top of the other lines, but I don’t know how to properly select the parentNode:

function onmouseover(d, i){
  var current_gene_name ="name"),
      current_gene_pcp =".line[name=" + current_gene_name + "]");
  p1 = this.parentNode
  p2 = current_gene_pcp[0].parentNode
  p3 = current_gene_pcp[0][0].parentNode

p1 works, but I wanted to make sure that this is a .line, so I preferred to use current_gene_pcp, but p2 returns <html></html> as the parent, even though p3 returns the proper <g></g>. This last version seems like a bug waiting to happen. Is there a better way?


A D3 selection is just a double-array wrapped around the element(s) selected. As you found with p3, you can dereference the arrays to find your first node, if you want. However, a better method does exist:

From the docs for selection.node():

Returns the first non-null element in the current selection. If the selection is empty, returns null.

In your case:

var dad = current_gene_pcp.node().parentNode;

However, if you don’t need the line other than the DOM handle, you might as well just get that directly:

// Search document-wide...
var dad = document.querySelector(".line[name=" + current_gene_name + "]");
// ...or only as a child of the current DOM element
var dad = this.querySelector(".line[name=" + current_gene_name + "]");