0

I'm using d3 and I want to append to an element that I'm appending.

svg.append('g').attr('foo', 'bar')
    .selectAll('rect').data(data)
    .enter().append('rect')
        .attr('class', function(d) { return 'some-class' })
        .attr('y', 0)
        .attr('height', 42)
        .attr('x', function(d) { return d.x); })
        .attr('width', 9001);
        // hot damn would it be cool if I could just .append a span here...

I want to append a span to the elements I'm inserting, but I don't know how. People say to use appendTo but I don't know how that works with the selectAll, I tried looping over the elements and adding them but that isn't working either an I'm not sure why.

svg.append('g').attr('foo', 'bar');
_.each(data, function(d) {
    var rect = $('rect')
        .attr('class', function() { return 'some-class'; })
        .attr('y', 0)
        .attr('height', 42)
        .attr('x', function() { return d.x; })
        .attr('width', 9001)
        .append('<span class="cool-class">Spantastic!</span>');

    svg.append(rect);
});

I am not very familiar with this type of thing, I've made a few changes guessing how it should be, but nothing works (d3 contains about the object having no method "indexOf"). Any ideas? Thanks.

user1756980
  • 3,807
  • 4
  • 16
  • 13
  • 1
    You should be able to simply add `.append("span")` to the end of your first block of code. That will append a `span` element to each `rect`. – Lars Kotthoff Dec 02 '13 at 21:17
  • @LarsKotthoff thank you! I had been doing it wrong and tried to find the answer on google and it saw people talking about how you couldn't use .append .append because the original object was returned not the new one, and I thought that was my problem. – user1756980 Dec 02 '13 at 21:37
  • Cool, I'll add that as an answer for reference. – Lars Kotthoff Dec 02 '13 at 21:38

1 Answers1

0

You should be able to simply add .append("span") to the end of your first block of code. That will append a span element to each rect.

Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204