James Riordan
James Riordan

Reputation: 53

D3 select on ID parentNode

If my HTML is

<html>
<script src="d3.min.js" type="text/JavaScript"></script>
 <body>
   <div id="borderdiv">meh</div>
 </body>
 <script type="text/JavaScript">console.log((d3.select("#borderdiv")[0]));</script>
</html>

and I d3.select("#borderdiv"), should the result have parentNode as body or html? I'd expect the former but get the latter.

Please note that in practice I do not actually want the parentNode: rather this is a minimal case of a behavior that I find unexpected. I want to know if it's a bug in d3.

Upvotes: 3

Views: 334

Answers (3)

rphv
rphv

Reputation: 5537

In d3.js selections, each selection is an array of arrays of elements, where the sub-arrays

have additional methods [bound] to the array so that you can apply operators to the selected elements.

Thus d3.select("#borderdiv")[0] is an array (with parentNode set by d3.js to the DOM root), not a node itself.

What you want is

d3.select("#borderdiv")[0][0].parentNode.

EDIT:

From the docs:

Grouping by selectAll also affects subsequent entering placeholder nodes. Thus, to specify the parent node when appending entering nodes, use select followed by selectAll:

d3.select("#borderdiv")
  .selectAll("#borderdiv")
  .data("ipsum dolor sit amet".split(" "))
  .enter()
  .append("div");

Upvotes: 1

Fawzan
Fawzan

Reputation: 4849

interesting question, Let me share my answer.

If you are really interested in the immediate parent node (In your case body) here is a hustle free way to get it.

var parent = d3.select("#borderdiv").select(function(){
   return this.parentNode;
})

I am bit of allergic to use array indexing for these kind of things. So I prefer using this method.

Upvotes: 1

Jonas Meinerz
Jonas Meinerz

Reputation: 622

Actually a better way is to nevermind d3 here. It's much simpler and cleaner if you just write it in plain javascript:

document.getElementById('borderdiv').parentNode();

Upvotes: 1

Related Questions