简体   繁体   中英

D3.js - Append objects outside of the selection

How do you select a div and then create a new div right below it?

 function addContainer(row) { row++ d3.select('body') .append('div') .attr('class', `#container${row}`) .attr("onclick", `addContainer(${row})`) .text("Container " + `${row}`) }
 <div id="container0" onclick="addContainer(0)" >Container 0</div> <script src="https://d3js.org/d3.v5.min.js"></script>

Everything works fine except for the part that I want the added div to be exactly below the div I clicked on and not at the very bottom. So my idea was that instead of selecting the body I select the id of the div I clicked on and then append a new div. However this adds a div within the div and not below it.

So how do I append it outside of the selection or is there a better way to do it?

Here's one approach to do that: Use d3.insert .

And due to the this issues while binding events onclick on HTML elements, I've moved the event binding and handling to the JS section.

This is how I'm appending a <div> as the next sibling to the selected (clicked) element: this.parentNode.insertBefore(this.cloneNode(deep), this.nextSibling)

Code:

 d3.select('#container0').on('click', addContainer); function addContainer(row) { if(!row) row = 0; row++ d3.select(this).select(function () { return this.parentNode.insertBefore(document.createElement('div'), this.nextSibling); }) .attr('class', `#container${row}`) .on('click', function () { addContainer.call(this, row); }) .text("Container " + `${row}`) }
 <div id="container0">Container 0</div> <script src="https://d3js.org/d3.v5.min.js"></script>

Notice the addContainer.call(this, row) to bind the this used while selection.

Hope this helps. And about the container number , it adds +1 to the bound element's number. If you want the container number to keep on increasing, just declare the row outside and take it out while calling the function (as this'll help the div s to have unique IDs). And do check the DOM if it's inserting the elements correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM