Appending when using selectAll in d3

315 views Asked by At

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.

1

There are 1 answers

0
Lars Kotthoff On

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.