D3.js preend (similar to jQuery preend)

I like using append in D3 and I am looking for preend.

Does it exist in D3?

+63
javascript prepend
Oct 07 '14 at 11:09
source share
2 answers

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 the selected item. Check the documentation to find out more.

Another possible way to insert elements in front of 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> 
+112
Oct 07
source share

Selection.lower ()

selection.lower() will place the item as the first child of its parent.

Together with d3 append , selection.append().lower() can copy jQuery prepend

Starting with D3 v4 +, D3 has methods selection.raise() and selection.lower() . Most often they are used to move elements in the SVG, so some elements are displayed on top of others, where the ordering of the SVG elements in the DOM determines the drawing order. But they can be used for any element in the DOM.

Here is a brief demonstration using div elements and paragraphs:

 var div = d3.select("div"); div .append("p") .text("Inserted") .lower(); console.log(div.html()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <div id="div"> Text <p> Child Paragraph </p> </div> 

The fragment accepts a div with the following contents:

 Text <p> Child Paragraph </p> 

And uses d3 to add a new paragraph and then omit it so that the structure is as follows:

 <p>Inserted</p> Text <p> Child Paragraph </p> 

And for comparison with jQuery prepend:

 var div = $("div"); div .prepend("<p>Inserted</p>"); console.log(div.html()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="div"> Text <p> Child Paragraph </p> </div> 

More information

Selection.lower () is implemented like this (see the documentation for more information):

 selection.each(function() { this.parentNode.insertBefore(this, this.parentNode.firstChild); }); 
0
Mar 31 '19 at 19:55
source share



All Articles