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?
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.
parentNode gives the parent, while . parentElement gives undefined.
The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.
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, returnsnull
.
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 + "]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With