Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...