1

I have a variable that selects a g tag (we will call her all_g). I wanna select some content of this g.

So here's what's in my g tag : The G-tag

I wanna reach all others afterText content, like this one, that contains "19". So i tried to do :

var all_aftertext = all_g.selectAll(".node tspan.aftertext");

But it returns an empty NodeList. How can I select this easily ?

This is the function on my code where i try to retreive all of the aftertext :

function add_total_svg(all_g, cell) {
    var all_aftertext = all_g.selectAll(".node tspan.aftertext");
    //for (var i = 0; )
    console.log(all_aftertext);
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Total");
}

And here is my entire code :

<!DOCTYPE html>
<head>

    <meta charset="utf-8"> 
    <title>Graphique DPGF</title>
    <style>

.node rect {
  cursor: pointer;
  fill: #fff;
  fill-opacity: 0.5;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

#div { display: table-row; }
#div .cell { display: table-cell; vertical-align: top;}

.node text {
  font: 10px sans-serif;
  pointer-events: none;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

//Initialisation des variables, marge, hauteur, incrementation 'i' etc ..
var margin = {top: 30, right: 20, bottom: 30, left: 20},
    width = 400,
    barHeight = 20,
    barWidth = (width - margin.left - margin.right) * 0.8;

var cursorX;
var loop;
var cursorY;
//stack_nb variable
var nb_data = [
    [], [], []
];
var nb_tmp = 0;
var nb = 0;
var i = 0;
var do_it = 0;

document.onmousemove = function(e){
        cursorX = e.pageX;
        cursorY = e.pageY;
    }

var i = 0,
    duration = 0,
    root;


var path = [];
path[0] = "A.json";
path[1] = "A.json";
path[2] = "A.json";
var value = [];
create_a_tree_obj(path);


function multiple_click() {
    //onmousemove = function(e){console.log("mouse location:", e.clientX, e.clientY)}
    if (cursorX >= 0 && cursorX < 600) {
        simulateClick(cursorX + 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX + 1200 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else if (cursorX >= 600 && cursorX < 1200) {
        simulateClick(cursorX - 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX + 600 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else if (cursorX >= 1200) {
        simulateClick(cursorX - 600 - window.pageXOffset, cursorY - window.pageYOffset);
        simulateClick(cursorX - 1200 - window.pageXOffset, cursorY - window.pageYOffset);
    }
    else
        console.log("no , cursorX = " + cursorX + " , cursorY = " + cursorY);
}

//Changez le last_svg
function add_total_svg(all_g, cell) {
    var all_aftertext = all_g.selectAll(".node tspan.aftertext");
    //for (var i = 0; )
    console.log(all_aftertext);
    cell.attr("class", "total").attr("id", "total");
    cell.select("#title").text("Total");
}  

function stack_nb(str_nb) {
    if (nb > nb_tmp) {
        nb_tmp = nb;
        i = 0;
    }
    nb_data[nb][i] = Number(str_nb);
    i++;
}


function create_a_tree_obj(path) {
    var i = 0;
    var div;
    var cell;
    var svg_array = [];

    if (i === 0) {
        div = d3.select("body").append("div")
            .attr("id", "div");
    }
    for (i ; path[i]; i++) {
        cell = div.append("div").attr("class", "cell").attr("id", "cell");
        cell.append("p").text(path[i]).attr("style", "font-family: Helvetica").attr("id", "title");
        svg_array[i] = cell.append("svg")
        .attr("id", "d" + i)
        .attr("width", 600) // + margin.left + margin.right)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
        add_the_tree_graph(svg_array, path, i);
    }
    add_total_svg(svg_array[i - 1], cell);
}

function add_the_tree_graph(svg_array, path, i) {
    var root = [];

    d3.json(path[i], function(error, json) {
        if (error) throw error;
        for (; path[i]; i++) { 
            root[i] = d3.hierarchy(json);
            root[i].x0 = 0;
            root[i].y0 = 0;
            nb = i;
            do_it = 1;
            update(root[i], svg_array[i], "d" + i, root);
        }
    });
}    


function update(source, svg_var, svg_id, all_sources) {
  // Compute the flattened node list.
    var nodes = source.descendants();
    var height = Math.max(50, nodes.length * barHeight + margin.top + margin.bottom);

    document.getElementById(svg_id).setAttribute("height", height);
    d3.select(self.frameElement).transition()
      .duration(duration)
      .style("height", height + "px");

  // Compute the "layout". TODO https://github.com/d3/d3-hierarchy/issues/67
  var index = -1;
  source.eachBefore(function(n) {
    n.x = ++index * barHeight;
    n.y = n.depth * 20;
  });

  // Update the nodes…
  var node = svg_var.selectAll(".node")
    .data(nodes, function(d) { return d.id || (d.id = ++i); });

  var nodeEnter = node.enter().append("g")
      .attr("class", function (d) {
          return 'node ' + (d.children ? '' : 'child'); 
      })
      .attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
      .style("opacity", 0);

  // Enter any new nodes at the parent's previous position.
  nodeEnter.append("rect")
      .attr("y", -barHeight / 2)
      .attr("height", barHeight)
      .attr("width", barWidth)
      .style("fill", color)
      .on("click", function(d) {
      if (d.children) {
            d._children = d.children;
            d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
      update(source, svg_var, svg_id, all_sources); //recursion pour re-afficher la page dynamiquement.
      loop = 1;
      return;
    });
    nodeEnter.append("text")
    .attr("dy", 3.5)
    .attr("dx", 5.5)
    .each(function (d) {
    if(d.data.attributes.indexOf('|') > -1) {
        var beforeText = d.data.attributes.substr(0,   d.data.attributes.indexOf('|')).trim(),
        afterText = d.data.attributes.substr(d.data.attributes.indexOf('|')+1, d.data.attributes.length).trim();
        d3.select(this).append('tspan').classed('beforetext', true).text(beforeText);
        var afterTextSpan = d3.select(this).append('tspan').classed('aftertext', true).attr("id", "afterText").text(afterText);

    // position aftertext
        var temp_text = svg_var.append('text').classed('temp_text', true).text(afterText);
        afterTextSpan.attr('x', (288 - afterText.length * 6) - 5)
        temp_text.remove();
    } else {
        d3.select(this).text(d.data.attributes);
    }
  });
  // Transition nodes to their new position.
    nodeEnter.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1);
    node.transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
      .style("opacity", 1)
    .select("rect")
      .style("fill", color);

  // Transition exiting nodes to the parent's new position.
  node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
      .style("opacity", 0)
      .remove();
}
function simulateClick(x, y) {
    var s = d3.select(document.elementFromPoint(x, y));
    s.on("click")(s.datum());
}

setInterval(function(e){
    if (loop === 1) {
        multiple_click();
        loop = 0;
    }
}, 1);

function color(d) {
  return d._children ? "#3182bd" : d.children ? "#c6dbef" : "#fd8d3c";
}

</script>
<br>

And the A.json file :

{"attributes": "DPGF", "children": [{"attributes": "LOT:  nom 13.CVC", "children": [{"attributes": "Tous_DPGF:  Profondeur 1", "children": [{"attributes": "Poste:  Rang Rang 1 | 19", "children": [{"attributes":"Prix unitaire | 0.0"}, {"attributes":"Unité | 19.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     40", "children": [{"attributes":"Prix unitaire | 20.0"}, {"attributes":"Unité | 20.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     44", "children": [{"attributes":"Prix unitaire | 21.0"}, {"attributes":"Unité | 23.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     49", "children": [{"attributes":"Prix unitaire | 24.0"}, {"attributes":"Unité |25.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     53", "children": [{"attributes":"Prix unitaire |26.0"}, {"attributes":"Unité |27.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 1 |     93", "children": [{"attributes":"Prix unitaire | 28.0"}, {"attributes":"Unité | 65.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}, {"attributes": "Tous_DPGF:  Profondeur 2", "children": [{"attributes": "Prix total", "children": [{"attributes":"Prix unitaire | 31.0"}, {"attributes":"Unité | 65.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}, {"attributes": "Tous_DPGF:  Profondeur 3", "children": [{"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire | 35.0"}, {"attributes":"Unité| 35.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire |36.0"}, {"attributes":"Unité |36.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire| 37.0"}, {"attributes":"Unité |37.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire    | 38.0"}, {"attributes":"Unité| 38.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire  |39.0"}, {"attributes":"Unité   |39.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire | 40.0"}, {"attributes":"Unité |41.0"}, {"attributes":"Quantité"}, {"attributes":"Prix total"}]}, {"attributes": "Poste:  Rang Rang 4", "children": [{"attributes":"Prix unitaire             | 42.0"}]}]}]}]}]}]}]}]}

Thanks.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
Zahreddine Laidi
  • 560
  • 1
  • 7
  • 20
  • 3
    dont just assume people can understand you, put your code here – Chris Li Sep 20 '18 at 08:24
  • 3
    The picture shows us what the DOM looks like, but it's really hard to see why your node list is empty unless you show the code. Please read this: https://stackoverflow.com/help/mcve – ksav Sep 20 '18 at 08:31
  • 1
    There is obviously something else going wrong here as the query you've written should retrieve that node. That is why it is important to post a minimal complete example instead of a photo. – i alarmed alien Sep 20 '18 at 08:31
  • 1
    Sorry about that, I edited and put my code. – Zahreddine Laidi Sep 20 '18 at 08:34

1 Answers1

1

The problem here is quite simple to spot, but quite complicated to understand for someone who doesn't know asynchronous code. So, let's start with a joke:

There are two types of programmers: and those who don't. Those who understand asynchronous code...

So, what's the problem here? If you look at your code inside create_a_tree_obj you'll see that it calls, in that order:

  1. add_the_tree_graph
  2. add_total_svg

Therefore, since add_the_tree_graph runs before add_total_svg those <tspans> should be there, right?

Wrong. Inside add_the_tree_graph you have this:

d3.json(path[i], function(error, json) {
    if (error) throw error;
    //etc...
});

And that's the asynchronous code we talked about. d3.json's callback will not run immediately, and by the time add_total_svg is called, there is no <tspan> there yet.


Although this issue have been explained several times at S.O. — this question being the best dupe target — I reckon the code here deserves a specific answer, given the not so obvious position of the asynchronous code.

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171