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

d3.js, javascript

Solution

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 + "]");

Problem

I've created the following document: ``` <g> <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>​ ... </g> ``` 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 = d3.select(this).attr("name"), current_gene_pcp = d3.select(".line[name=" + current_gene_name + "]"); p1 = this.parentNode p2 = current_gene_pcp[0].parentNode p3 = current_gene_pcp[0][0].parentNode //p.appendChild(this); } ``` `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?

Original source

Related problems