Search code examples
javascriptd3.jsprepend

D3.js prepend (similar to jQuery prepend)


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

Does this exist in D3?


Solution

  • 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>