Ranjith
Ranjith

Reputation: 179

Treemap Onclick d3.js

How to get the value of a rectangle from treemap while on click using d3.js? HTML body is as follows,

<g class="depth">
    <g>
        <title>"ABC"</title>
        <g>"My rectangle tag here"</g>
    </g>
    <g>
        <title>"DEF"</title>
        <g>"My rectangle tag here"</g>
    </g>
</g>

I want to access the title tag value once I click the rectangle.

Upvotes: 3

Views: 1700

Answers (2)

murli2308
murli2308

Reputation: 3004

Short and sweet

d3.selectAll('rect').on('click', function() {
  var title = d3.select(this.parentNode.nextElementSibling).text();
});

if title element is before the rect element then use

var title = d3.select(this.parentNode.previousElementSibling).text();

Use d3 selectors and text function to get the value you want

Working Fiddle

Upvotes: 1

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

Using D3, you can select one rectangle on click and get the title this way (regarding the specific SVG structure you provide in your question):

d3.selectAll("rect").on("click", function(){
  var title = this.parentNode.parentNode.getElementsByTagName("title")[0].childNodes[0];
  console.log(title);
});

The value of the tag title is stored in var title. Here is a fiddle: https://jsfiddle.net/gerardofurtado/ow9a0vzd/

Upvotes: 3

Related Questions