Consider this simple block of HTML:
<div id="somediv">
<btn id="somebutton">Abc</btn>
<div class="nested">
<span id="span1">Blah blah blah</span>
<span id="span2">Bleh bleh bleh</span>
</div>
</div>
I'd like to recreate it, dynamically, using D3JS.
This works fine for this purpose:
(function() {
var somediv = d3.select( 'body' ).append( 'div' ).attr( 'id', 'somediv' );
somediv.append( 'btn' )
.attr( 'id', 'somebutton' )
.html( 'Abc' );
var nested = somediv.append( 'div' )
.attr( 'class', 'nested' );
nested.append( 'span' ).attr( 'id', 'span1' ).html( 'Blah blah blah' );
nested.append( 'span' ).attr( 'id', 'span2' ).html( 'Bleh bleh bleh' );
})();
…however, it's very verbose, with four commands and two temporary variables… Most of all, it's not easy to read – don't like it.
I'm looking for a way to do it in a single command.
So far, I have this:
d3.select( 'body' )
.append( 'div' )
.attr( 'id', 'somediv' )
.append( 'btn' )
.attr( 'id', 'somebutton' )
.html( 'Abc' )
.append( 'div' )
.attr( 'class', 'nested' )
.append( 'span' ).attr( 'id', 'span1' ).html( 'Blah blah blah' )
.append( 'span' ).attr( 'id', 'span2' ).html( 'Bleh bleh bleh' );
…however (as is to be expected), this results in constant nesting (i.e.: span2 is in span1, which is in div which is in btn which is in #somediv.)
Is there something in the D3 JS API that will let me return (to) the parent element to continue appending from it?