Search code examples
d3.jssvgdocumentfragment

d3.js. How to append documentFragment to SVG?


See my example on jsfiddle. One red rect exists as static markdown. Second green rect is appended using append method. Where is blue rect? You can see with any document inspector that blue rect already inserted within svg element, but it is not visible. Why? I try to insert big amount of rectangles into SVG using documentFragment but they all are not visible...


Solution

  • It seems you have to help d3 by telling it the rect is an svg rect and not some mythical html rect element. E.g.

    var svg = d3.select("svg");
    svg.append("rect")
        .attr("width", 50)
        .attr("height", 50)
        .attr("x", 50)
        .attr("y", 0)
        .attr("fill", "green")
    var documentFragment = document.createDocumentFragment();
    d3.select(documentFragment).append("svg:rect")
        .attr("width", 50)
        .attr("height", 50)
        .attr("x", 100)
        .attr("y", 0)
        .attr("fill", "blue")
    console.log(documentFragment);
    svg.node().appendChild(documentFragment);
    

    Not sure but this may be a bug in d3.