D3: Select and change external SVG?

Can I select and change elements in the built-in (external) SVG created in Adobe Illustrator?

HTML:

<object data="circles.svg" type="image/svg+xml" id="circles"></object> 

circles.svg:

 <svg xmlns="http://www.w3.org/2000/svg" width="100px" height="100px" > <circle id="c_red" fill="#A00" stroke="#000" cx="40" cy="40" r="40"/> <circle id="c_grn" fill="#0A0" stroke="#000" cx="60" cy="60" r="40"/> </svg> 

d3 code:

 <script> var my_circles = d3.select("#circles svg").selectAll("circles"); my_circles.attr("fill", "black"); </script> 

Otherwise, I am open to other ways to do this. For example, something like this might work to select (which really finds SVG):

 var svg = document.getElementById('circles'); 

But how then to parse and change in D3? Bonus question: the best way to debug D3 selectors?

+4
source share
1 answer

This is really a nasty case, because you cannot use the DOM selector directly on embedded documents. Basically, you need the selector "#circles > circle" , but in this case it will not work. So you need something pretty ugly like

 var my_circles = d3.select(document.getElementById("circles").contentDocument) .selectAll("circle"); 

I find the Javascript console quite useful for debugging selectors. Just enter what you want to check and see if the things you want are back.

The problem is that the above code only works after the object has been loaded. Even when using something like jQuery .ready() this is not enough. A quick and dirty solution is to repeatedly check if the elements are present until they are:

 function changeColor() { var sel = d3.select(document.getElementById("circles").contentDocument) .selectAll("circle"); if(sel.empty()) { setTimeout(changeColor, 100); } else { sel.attr("fill", "black"); } } changeColor(); 

Full example here .

+6
source

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


All Articles