Cris
Cris

Reputation: 2021

How to use D3 to append several html line of codes

I need to add all this code by using D3:

 <fieldset style="width: 280px; margin-left: 45px; position: absolute;" >
        <legend>Options</legend>
          <d>Rotation: </d>&nbsp;
          <select id="rotation" style="position: center;">

          </select>  &nbsp; 
          <d>Inclination: &nbsp;</d>
          <select id="inclination" style="position: center;">

          </select>
     </fieldset>

The reason why I need D3 is that I want to add this snippet of code only after a certain task has been completed and only afterwards I want to populate the two Select elements.

How can I do that? Thank you very much

Upvotes: 1

Views: 201

Answers (1)

double.emms
double.emms

Reputation: 553

You can use d3.html().

Just start by selecting the outlet where you want the controls to be placed, and then use the html method to insert them.

d3.select('#where-you-want-the-output').html('<fieldset style="width: 280px; margin-left: 45px; position: absolute;" ><legend>Options</legend><d>Rotation: </d>&nbsp;<select id="rotation" style="position: center;"></select>  &nbsp; <d>Inclination: &nbsp;</d><select id="inclination" style="position: center;"></select></fieldset>');

And if you want to keep the formatting in your source code, you can use \ to make a multi-line string.

d3.select('body').html(
'<fieldset style="width: 280px; margin-left: 45px; position: absolute;" > \
  <legend>Options</legend> \
    <d>Rotation: </d>&nbsp; \
    <select id="rotation" style="position: center;"> \
 \
    </select>  &nbsp; \
    <d>Inclination: &nbsp;</d> \
    <select id="inclination" style="position: center;"> ]
 \
    </select> \
</fieldset>');

If you provide an argument to d3.html it will set the html for that selection, but if you call it without an argument, it will return what's already there. So, if you have existing content you can pull it as a string like this...

d3.select('#where-i-want-to-add-more-content').html(
  d3.select('#where-i-want-to-add-more-content').html() + // get what's already there...
  '<fieldset style="width: 280px; margin-left: 45px; position: absolute;" > \
    <legend>Options</legend> \
      <d>Rotation: </d>&nbsp; \
      <select id="rotation" style="position: center;"> \
   \
      </select>  &nbsp; \
      <d>Inclination: &nbsp;</d> \
      <select id="inclination" style="position: center;"> ]
   \
      </select> \
  </fieldset>'
);

...although, at this point, it's arguably getting a little messy, and you might be better off having a specific container for the message that you're okay overwriting the contents of every time. Or using d3.append to build your output programmatically.

Hope this helps.

Upvotes: 2

Related Questions