Creating a d3 selection over an existing highlighted SVG element

I have a component in JavaScript that will provide the <svg> element to its host. I want to populate an SVG element with d3.js.

If I let d3.js create an SVG element and add it to <body> , then everything will work as expected:

 var chart = d3.select('body').append('svg'); 

However, I already have an SVG element. I want my code more like:

 var svg = document.createElement('svg'), chart = d3.select(svg); 

This last approach fills the SVG element (as seen in the Chrome Developer Toolbar), but it does not display properly.

Am I really wrong?

I don't mind if d3 creates an SVG element, if it does not attach it to the DOM, and I can access it.


EDIT I created a jsFiddle that reproduces my problems . You can switch the APPROACH variable between 1 and 2 to see alternative approaches. I see this problem in both Chrome and Firefox (latest versions on Ubuntu 13.04.)


EDIT 2 I took a screenshot showing the working and non-working versions side by side:

LR5e9At.png

You can see that the element trees are basically the same. However, on the non-working version (on the left) in the Styles panel (to the right of the element tree) some user agent rules are missing. I have no idea why this should be otherwise. I would suggest that it was a bug in Chrome, but the same behavior is visible in Firefox.

+6
source share
1 answer

The problem is that you are creating an SVG element in the HTML namespace where it is not interpreted correctly. If you replace

 var svg = document.createElement('svg'); 

with

 var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); 

It works great. D3 will take care of this for you by setting the namespace automatically.

+4
source

Source: https://habr.com/ru/post/948854/


All Articles