Adding a dynamic attribute name to a selection

I have this:

g.append(function(d) {
  return document.createElementNS("http://www.w3.org/2000/svg", d.shape);
})

Where d.shape can be circle or polygon. Now depending on the shape, I would like to add an attribute. For circle:

.attr('r', 12)

For polygon:

.attr('points', '05,30 15,10 25,30'))

But I do not know how to add this variable pair attribute name/value. Is it possible? A related jsbin is here.

Answers


I would either use a selection filter for this, filtering on the nodeName property of the element:

d3.selectAll("top_level_selector") //or use existing selection from appending
.filter(function(d,i){
    return this.nodeName == 'circle';
})
.attr("r", 12);

- https://github.com/mbostock/d3/wiki/Selections#wiki-filter

Or possibly just check inside the attribute function for correct nodetype :

selection
.attr('r',function(d,i){
    if(this.nodeName =='circle'){ return 12 }
});

I'm not positive but I don't think this will present a problem when it tries to assign an "r" attribute of undefined to the non-circle elements (and so on for 'points' on circle, etc).


Need Your Help

how to trigger a zone file save from dnspython after an update

python python-2.7 dnspython

I am using dnspython to perform dynamic DNS updates using a syntax similar to:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.