J. Doe
J. Doe

Reputation: 693

D3.js does not append HTML

I'm trying append to my existed HTML code the next:

<div id="bar-1" class="bar-main-container azure">
    <div class="wrap">
        <div class="bar-percentage" data-percentage="52"></div>
        <div class="bar-container">
            <div class="bar"></div>
        </div>
    </div>
</div>

for this I did:

var stats = d3.select("#language_stats")
    .append("div").attr("class", "bar-main-container azure")
    .append("div").attr("class", "wrap")
    .append("div").attr("class", "bar-percentage").attr("data-percentage", "52")
    .append("div").attr("class", "bar-container")
    .append("div").attr("class", "bar");

where

<div id="language_stats"></div>

but this code does not appending into my HTML. The block runs but does not append anything. What is the problem?

Also I'm a little bit struggled with this part,

<div class="bar-percentage" data-percentage="52"></div>

where closing </div> and data-percentage included.

Thanks in advance!

Upvotes: 1

Views: 993

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Since this is the structure you want to reproduce...

<div id="bar-1" class="bar-main-container azure">
    <div class="wrap">
        <div class="bar-percentage" data-percentage="52"></div>
        <div class="bar-container">
            <div class="bar"></div>
        </div>
    </div>
</div>

... you have to break the selection, otherwise you'll end up with a matryoshka doll of divs (a div inside a div inside a div...).

This is the code, pay attention to innerDiv1 and innerDiv2:

var stats = d3.select("#language_stats")
  .append("div")
  .attr("class", "bar-main-container azure")
  .append("div")
  .attr("class", "wrap");

var innerDiv1 = stats.append("div")
  .attr("class", "bar-percentage")
  .attr("data-percentage", "52");

var innerDiv2 = stats.append("div")
  .attr("class", "bar-container")
  .append("div")
  .attr("class", "bar");

console.log(d3.select(".bar-main-container").node())
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="language_stats"></div>

Click "Run code snippet" and inspect the console in your browser (which will expand the element), not the Stack snippet result.

Upvotes: 2

Related Questions