D3: how to shorten the attr()/style() code?

Im currently working on the d3 curriculum. Right from the start i found the multiple use of attr()/style() syntax very inconvenient and was already thinking of a way to come around it. Contrary to my expectations, attr() wont accept object as parameter, one which could hold multiple attributes and their respective values, or at least thats the case with codepen d3 module. Im sure there must a a technique to reduce the code and im here to ask fellow coders for some hints :slight_smile: . I wonder is there a way to make a custom attr() method, one that could attach multiple attributes at time, something like d3.select('svg).myAttr(...), but my skills are not sufficient. So far i came up with simple function, which would accept as arguments an element and an object with attributes to attach to it:

function myAtr(elem, obj){
  for (key in obj){
    elem.attr(key, obj[key])

But obviously it cant be applied similarly to the d3 syntax(which i wish), by applying it as a method (selection.method())

In d3, this is how it is, for better or worse. All the d3 code I’ve seen handles styles and attributes one at a time by chaining them all together like everything else.

Not that your idea is a bad one, but I suspect that to add the functionality you want, you would have to modify d3 directly and add a list/object version of the attr or style methods and make sure they are chainable.

You can duck the style issue by using a style sheet, at least for the styles that are not dynamically altered.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.