Learn SVG attr method

Hi,
In selection.attr('width', w).attr('height',h) have a possibility that pass one time this two or more attributes in only one method .attr() or .style()??

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Learn About SVG in D3

Link to the challenge:
https://www.freecodecamp.org/learn/data-visualization/data-visualization-with-d3/learn-about-svg-in-d3

attr({ width: 100, height: 100 })

Hello JorgeLAB,

After some searching, I came across this post, and it seems that with the newest version of d3 (v5) does not support this out-of-the-box, but there is an extension called d3-selection-multi. I don’t know if you can use it on the freecodecamp challenges, but when you get to the projects, there is no reason you couldn’t include it in your code.

Like the README says, you can NPM install it like this: npm install d3-selection-multi and then use it like this:

d3.select("body").append("div")
    .attrs({
      title: "A cheery, timeless greeting.",
      class: "greeting"
    })
    .text("Hello, world!");

This is equivalent to

d3.select("body").append("div")
    .attr("title", "A cheery, timeless greeting.")
    .attr("class", "greeting")
    .text("Hello, world!");

It just uses attrs instead of attr.

1 Like

Ah, it’s been years since I even played around with d3 (and it’s such a hyper-specialised tool I’ve never had reason to even look at it since), I just remembered I used to be able to do that. On phone so I can’t check whether the object syntax works or not with the version FCC are using, but OP defo won’t be able install add-ons

DanCouper,

According to the StackOverflow post in my previous comment, this syntax does not work for the latest versions of D3 (versions 4 and 5). Instead, the d3-selection-multi library is used.

Yah, I didn’t think he’d be able to use it in challenges, but I figured he could try it out in the projects when he’s on Glitch or a local editor.

And yah, I always forget d3 even exists, until I see questions on this forum lol.

1 Like