Set ID attribute on Snap.svg chart

I use the Snap.svg API, and I have three graphics that I need to select in my CSS for styling. So in order to distinguish between them, I need to give them an identifier or class name.

This is how I create an element:

var draw = Snap(100, 75); c = draw.polyline(0,0, 50,75, 100,0, 0,0); c.attr({ fill: "black" }); 

This is the result:

 <svg height="75" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg"> <polyline points="0,0,50,75,100,0,0,0" style="" fill="#000000"></polyline> </svg> 

Here is what I need for the result:

 <svg id="graphic_1" height="75" version="1.1" width="100" xmlns="http://www.w3.org/2000/svg"> <polyline points="0,0,50,75,100,0,0,0" style="" fill="#000000"></polyline> </svg> 
+7
javascript svg
source share
2 answers

Update

I raised a question about GitHub, and it looks like this will be fixed in the next version . So far in the development branch you can use Element.attr :

 var draw = Snap(100, 75); draw.attr({ id: 'graphic_1' }); 

I leave the original answer below because:

  • at the time of writing, this does not work in the master (release) version; and
  • The method described for direct access to the underlying DOM node may be useful to others in the future or to those using an earlier version of Snap.svg.

It is not documented, but inside Snap.svg stores the DOM node in the node property. So you can set the canvas ID like this:

 draw.node.id = 'graphic_1'; 

Alternatively, if you prefer to avoid undocumented methods, you can create an element with the first identifier and use it directly:

 <svg id="graphic_1" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="75"></svg> 
 var draw = Snap("#graphic_1"); 
+13
source share

With Snap version 0.2.0 the .attr() method will work as expected

 var draw = Snap(100, 75); draw.attr({id: "graphic_1"}); 

but with Snap version 0.1.0 I had a modification of snap.svg.js (approximately line 4338) for this to work.

 var availableAttributes = { svg: { id : "", }, 
+5
source share

All Articles