Ann
Ann

Reputation: 65

Access the text within SVG object using d3js

I am new to d3js and am trying to get the text value from SVG element. Below is my code html and javascript:

HTML Before d3.json load:

    <div id="model_container" style="position: fixed; top: 0px; bottom: 0px; left: 0px; right: 20%">

   </div>
  <span>
      <button onclick="getAllMapReactions();">ADD</button>
    </span>

HTML After d3.json load:

<div id="model_container" style="position: fixed; top: 0px; bottom: 0px; left: 0px; right: 20%">
.
.
.
.
 <g id='reactions'>
     <g id='r0' class='reaction'>
       <g class='reaction-label-group' transform='translate(360,500)'>
         <text class='reaction-label label'>HELLO</text>
       <g id='r1' class='reaction'>
         <g class='reaction-label-group' transform='translate(365,500)'>
           <text class='reaction-label label'>HELLO2</text>
</div>
  <span>
  <button onclick="getAllMapReactions();">ADD</button>
</span>

JavaScript:

d3.json(document.getElementById("model").value, function(error, data) {
     if (error) console.warn(error);
     var options = {menu: 'all', canvas_size_and_loc: { x: '200', y: '200', width: '5000', height: '5000' }};
     var b = escher.Builder(null, data, null, d3.select('#model_container'), options);


     b.map.new_reaction_from_scratch('GAPD',{ x: 350, y: 315 }, 90);
     b.map.new_reaction_from_scratch('PGK',{ x: 950, y: 315 }, 90);
     b.map.select_all();
   });



function getAllMapReactions() {
var reactionsVar = [];
      reactionsVar = d3.selectAll(".reaction-label-group").each(function (d) { reactionsVar.push(d3.select(this).text())});
      console.log(reactionsVar);

     alert(reactionsVar);
}

From above, I would like to extract the "HELLO" or "HELLO2" from <text class='reaction-label label'>HELLO</text>, however I get a svg object.

Upvotes: 2

Views: 700

Answers (1)

ccprog
ccprog

Reputation: 21811

You are selecting the the <g> element, not the <text>. Note the selector:

function getAllMapReactions() {
    var reactionsVar = [];
    d3.selectAll(".reaction-label-group text").each(function (d) {
        reactionsVar.push(d3.select(this).text())
    });
    console.log(reactionsVar);
}

Upvotes: 2

Related Questions