2

I'm trying to append two spans to a div using the following code:

    d3.select("#breadcrumb")
            .append("span")
            .attr("class","breadcrumb-link")
            .text(d.name)
            .append("span")
            .text("/");

But this adds elements like:

<div id="breadcrumb">
    <span>
        <span>
        </span>
    </span>
</div>

I want to add spans as siblings:

<div id="breadcrumb">
    <span>
    </span>

    <span>
    </span>
</div>

I know this can be done by first selecting the div and then using 2 statements for each span. Can I do this in a single chained statement?

rmoestl
  • 3,059
  • 5
  • 24
  • 38
ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • you can append them if divs are not already defined in html or select it if div exists in html. – SiddP Jun 02 '16 at 05:26
  • 2
    Possible duplicate of [Appending multiple non-nested elements for each data member with D3.js](http://stackoverflow.com/questions/21485981/appending-multiple-non-nested-elements-for-each-data-member-with-d3-js) – dariru Jun 02 '16 at 05:45
  • @echonax Oh, sorry. But I think an answer for this one is also provided in that previous question. Should that be okay? http://stackoverflow.com/a/33809812/2036808 – dariru Jun 02 '16 at 05:54
  • @Dar ah the 2nd one? Didn't see that one, my bad! Yes that's absolutely fine. I've added it to my answer – eko Jun 02 '16 at 05:55

1 Answers1

2

d3.js is based on the idea of data-driven documents. That said, typically you'll have data as an array that you gonna join with a selection.

With that in mind you could try a simple hack by joining the selection d3.select("#breadcrumb") with an "artificial" array [1, 2]. This would look like this:

d3.select("#breadcrumb").data([1, 2]).enter().append('span')...

Note, the call of enter().

If you wanna set different class attributes, you could stuff this data into the data array.

rmoestl
  • 3,059
  • 5
  • 24
  • 38