D3.js prepend (similar to jQuery prepend)

Mia picture Mia · Oct 7, 2014 · Viewed 28.9k times · Source

I like the usage of append in D3, and I'm looking for prepend.

Does this exist in D3?

Answer

Gilsha picture Gilsha · Oct 7, 2014

You can use

selection.insert(newElement[, anotherExistingElement])

For example:

selection.insert("div",":first-child")

The above code will insert a div before the first child of selected element. Check documentation to learn more.

Another possible way of inserting elements before any node (including plain texts):

var parentEl = d3.select("div").node();
parentEl.insertBefore(document.createElement("div"), parentEl.childNodes[0]);
<script src="https://d3js.org/d3.v3.min.js"></script>
<div>
  This is a plain text
  <a></a>
</div>