What is the best way to duplicate a DOM element or section?

I've been attempting to craft a stunning tree using D3.

For the nodes, I have an SVG "template" tucked away in a hidden div. Despite my efforts with various D3 functions to replicate the "template," none were successful.

The latest JavaScript snippet is:

...
var node = svg.selectAll("g.node")
            .data(nodes)
            .enter()
            .append("svg:g")
            .attr("transform",
                    function(d)
                    {
                        return "translate(" + d.y + "," + d.x + ")";
                    }
            );

var template_box = d3.select("#layer1");
console.log(template_box);

node.insert(template_box);
...

And here's a piece of the HTML:

...
    <body>
 <svg width="400" height="400">
 <g
 id="layer1"
 transform="translate(-208.375,-410.5)">
<rect
...

Best regards.

Answer №1

If you want to predefine shapes and then reuse them in different parts of your diagram, using svg's <defs> and <use> elements will yield better results. Take a look at this simple example for more information. You can create your shape like this:

<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">
 <defs>
   <g id="layer1" transform="translate(-208.375,-410.5)">
     <rect
     ...

Instead of duplicating the content of the <g>, you can simply reference its definition. Your code would look something like this:

var node = svg.selectAll("g.node")
  .data(nodes)
  .enter()
  .append("g")
  .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; } )

node.append("use")
  .attr("xlink:href","#layer1")

Remember that the xlink namespace is crucial in the svg definition.

UPDATE: Check out a complete working example of this approach here:

http://bl.ocks.org/explunit/5988971

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Utilize an external JavaScript file function within an AngularJS controller

I have an external JavaScript file with additional functions that I am trying to call from an Angular controller. Here is an example of the external.js file: ... ... function fun() { ... ... } ... ... The controller in question is called acccountCon ...

Automatically Parse Value by 100 in Angular FormGroup

Within my Angular form group, I have 3 fields. One of these fields serves as a tool for the user, automatically calculating the value based on another field. Essentially, when a user inputs a number, the tool field displays that value divided by 100. Here ...

Printing in HTML is limited to only one page

While printing an HTML table that can vary in length, I often encounter the issue of it printing multiple pages. Is there a way to limit the printing to just one page through coding? Yes, you can achieve this by using the option in the browser print dialog ...

Sharing Iframes across various Components within a Single Page Application (like Youtube)

Did you know that Youtube now lets you minimize the player while browsing the site? It's similar to the functionality on LolEsports.com with Twitch and embedded Youtube players. I'm interested in adding this feature to my own website. Here' ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

The website that had been functioning suddenly ceased operations without any modifications

It seems like this might be related to a JavaScript issue, although I'm not completely certain. The website was working fine and then suddenly stopped. You can find the URL here - Below is the HTML code snippet: <!DOCTYPE html> <html> ...

Exploring the contents of variables within the forEach iteration

One issue I've encountered involves accessing variables from a forEach loop that iterates over an array of objects, and trying to use those variables outside the loop. I attempted to declare variables and assign them values from the loop, but I found ...

Verifying conditions within an array of objects in JavaScript

Verify an array of objects based on certain conditions. The array of objects starts off empty. 1. If the array is empty and an action occurs, add an object to the array. 2. If the array already contains an object, check if it already exists. If it does, ...

How can you eliminate a specific element from an HTML document?

Utilizing localStorage can be tricky when it comes to keeping the JSON file hidden from being displayed on the HTML page. One approach I used involves sending the JSON file to the client once and then performing all logic using that file. To prevent the JS ...

Redirecting an Incorrect Request to a 404 Error Page

I am working on setting up a server that will allow users to access specific valid paths: localhost:9090/admin localhost:9090/project1 If a user enters any other invalid paths, they should be redirected to the root and then to the default path localhos ...

When buttons contain an image instead of text, event.target.value will be undefined

I'm facing an issue with two buttons that are almost identical, except one includes an image while the other has text content. I have added onClick event handlers to both of them. Oddly, the event.target.value for the image button is coming up as und ...

What could be causing this template literal to display each column on its own row instead of in a

Incorporating Bootstrap 4 on the front end and utilizing a straightforward template literal for string passing. My concern lies in the fact that the columns are being outputted into separate rows, a behavior I find perplexing. c ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Unlocking Google contact pictures using Google contacts API - A step-by-step guide

Exploring the Google contacts API with Node.js I've successfully retrieved all the contacts via the Google feed API, but without images https://www.google.com/m8/feeds/photos/media/faizy04%40gmail.com/ya29.ZAFTNcQ6sEue40gFqH5h8h91k8LO8Bwvf50NUgQKKms ...

Is there a way to pre-format a phone number field using jQuery?

Looking to create a phone number text field with a pre-formatted 10-digit structure, like this: |( ) - | allowing users to input numbers and have them fill in automatically: |(804) 479-1832| I came across a helpful script for formatting input d ...

One way to represent the carriage return character ( ) as text in HTML is by using a JavaScript function to create a

I have encountered a situation in which I need to display \r at the end of a string within a JavaScript function, but unfortunately it is not being displayed. <html> <body> <p>Click the button to create a PRE element.</p> < ...

What is the process for inheriting in JavaScript while also defining new prototype members as a singular object?

I find this code repetitive because it repeatedly uses Child.prototype: function Parent(a) { this.a = a; } function Child(a, b) { Parent.call(this, a); this.b = b; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = ...

How can server convert the data from Websocket 8.5, which sends `<Buffer>`, into JSON format?

Exploring websocket connections, I am looking to send a JSON object from the client to the server: const WebSocket = require('ws'); const wss = new WebSocket.Server({port: 8082}); wss.on("connection", (ws) => { console.log('s ...