Using d3.js to create an SVG at several divs

d3.js, html, javascript, svg

Solution

You can just append the SVG to your div with:

d3.selectAll("div.a").append("svg")

And if you want to select and act upon those SVGs after you made them just add a sub-select:

d3.selectAll("div.a").select("svg").append("rect").attr("height", 50).attr("width", 50)

Or you could class your SVGs and select them after you made them:

d3.selectAll("div.a").append("svg").attr("class", "divSVG")
d3.selectAll("svg.divSVG).append("rect").attr("height", 50).attr("width", 50)

Also, if you want them to appear before your

elements, use insert instead of append:

d3.selectAll("div.a").insert("svg", "p")

Problem

Suppose I have some HTML which looks like: ``` <html> <body> <div class = "a"></div> ... <div class = "a"></div> ... <div class = "a"></div> ... </body> <html> ``` where the ...'s are just paragraphs or other code. Problem: I'd like to be able to use d3.js to append an SVG at each of these div's. For example, let's say I want to make a rectangle like: ``` var svg = ((SOMETHING GOES HERE!)) .append("svg") .attr("width", w) .attr("height", h); var sep = svg.selectAll("rect") .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 100) .attr("height", 10) ``` How can I use the selectors on the first line to do this? I've tried `selectall()` and `select()` with various "div.a", ".", etc., things, but nothing seems to work.

Original source