This video is available to students only

Adding an SVG element

We learn how to create new elements inside of a d3 selection object.

Our wrapper object also has methods for manipulating the linked DOM element — let's use its append method to add a new SVG element.

If we log svg to the console, we'll see that it looks like our wrapper object. However, if we expand the _groups key, we'll see that the linked element is our new <svg> element.

One trick to make sure we're grabbing the correct element is to hover the logged DOM element. If we expand the _groups object and hover over the <svg> element, the browser will highlight the corresponding DOM element on the webpage.

svg selection with hover

If you're working within CodeSandbox, you'll need to do this in your browser's native dev tools.

On hover, the browser will also show the element's size: 300px by 150px. This is the default size for SVG elements in Google Chrome, but it will vary between browsers and even browser versions. SVG elements don't scale the way most DOM elements do — there are many rules that will be unfamiliar to an experienced web developer.

To maintain control, let's tell our <svg> element what size we want it to be.


This page is a preview of Fullstack D3 Masterclass

Start a new discussion. All notification go to the author.