S.Dan
S.Dan

Reputation: 1912

get the position details of a div inside an svg

I have included div's inside svg using foreignObject (I tried to use rect instead of div's, as in this example, but extendability-wise, the best option is div).

I want to add an svg circle at the end of each div of a particular class. The above example adds circles to all the elements, but now I want to filter them with a class selector. How can I achieve this with d3?

var leafnodes = new Array();
d3.select("#input-container-div").selectAll(".leaf")
    .each(function () {
        leafnodes.push(d3.select(this).style("top"));
     });

I used the above code but results in "0px" since the CSS of it does not define a value for "top".

I also tried the solution on this question, but for some reason it does not work.

Upvotes: 1

Views: 532

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

As you appended the divs using foreignObject, you set the x and y values to foreignObject, not to the divs. So, you need to get the values selecting the foreign objects, which are the parents of the divs.

Getting the "x" value of the parent (foreignObject) of each div:

var leafnodes = new Array();
d3.select("#input-container-div").selectAll(".leaf")
    .each(function () {
        leafnodes.push(d3.select(this.parentNode).attr("x"));
    });

For instance, giving this simple SVG, we can console.log the x and y positions:

var leafnodes = new Array();
d3.select("svg").selectAll("div")
    .each(function () {
     leafnodes.push({x: d3.select(this.parentNode).attr("x"),
y: d3.select(this.parentNode).attr("y")});
    });

console.log(JSON.stringify(leafnodes))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="300" style="border:1px red solid">
    <foreignobject x="40" y="20" width="100" height="100">
        <div style="border:1px green solid">I'm a div inside a SVG.</div>                
    </foreignobject>
    <foreignobject x="300" y="120" width="100" height="100">
        <div style="border:1px green solid">I'm another div inside a SVG.</div>                
     </foreignobject>
</svg>

Upvotes: 2

Related Questions