Home > Net >  D3.js - Add elements in HTML - <script></script> location
D3.js - Add elements in HTML - <script></script> location

Time:03-24

I was working with the following tutorial of D3.js: https://www.tutorialspoint.com/d3js/index.htm.

My issue is as follows:

  1. I'm aware of that the location inside the HTML is at the end of the . I mean, I usually put it here:
<body>
     <!-- HTML code -->

<script>
     <!-- JS code or external JS link -->
</script>
</body>

With this practice, what I'm looking is to run JS after the HTML content renders.

But! When I follow this practice using D3.js, what I discover is that D3.js renders what I add (using d3("html").append(something to append), after the script tags.

For example!

<!DOCTYPE html>
<head>
    <title>D3.js Test</title>
</head>
<body>
<div >
    <h1>I want the D3.js content after this div (but not inside the div)</h1>
</div>

<script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
<script>
    d3.select("html").append("p").text("I get this text after the script tags");
</script>
</body>
</html>

I'm getting the content as follows:

<!DOCTYPE html>
<html>
<head>
    <title>D3.js Test</title>
</head>
<body>
<div >
    <h1>I want the D3.js content after this div (but not inside the div)</h1>
</div>

<script type="text/javascript" src="https://d3js.org/d3.v4.min.js"></script>
<script>
    d3.select("html").append("p").text("I get this text after the script tags");
</script>`
</body><p>I get this text after the script tags</p></html>

Questions!

  1. Is the position of the tag correct?
  2. Is there a possibility to keep the flow without adding a to anchor the expected new tag?

Thanks!!!

CodePudding user response:

You can use selection.insert() to insert an element instead of appending it to the DOM. The second argument to that method determines where the newly created element is put into the DOM tree. If you just want to put it in front of the first <script> element you can do something like:

d3.select("body").insert("p", "script")   // <-- insert before first <script>

If you need to place it after the <div>, no matter what the next element might look like, you can use the adjacent sibling combinator to select the sibling element directly following the <div> like so:

d3.select("body").insert("p", "div   *")  // <-- insert before next element following div
  • Related