Anders Persson
Anders Persson

Reputation: 337

How to use my own ids to identify an element

I have information in a db with unique ids. When drawing with svg.js I would like to store the id in svg and then later be able to find the svg element by searching for the ids from the db.

I came up with two alternatives.

  1. Use the SVG.select, https://svgjs.dev/docs/2.7/referencing/#using-css-selectors , that returns elements that match a specific class. I can then give each element a specific class name calcualted from the db-id

  2. Using the data(), https://svgjs.dev/docs/2.7/manipulating/#data , to store and get my db-id.

Any suggestions or comments?

I tried to use select, alternative 1 above, but did not get it to work.

I then tried a third alternative by setting the id:

circle1.attr('id', 'myid1');

and then

var element = SVG.get('myid1')

and that works but I am not sure if setting the id will break anything within the implementation of svg.js

Upvotes: 1

Views: 555

Answers (1)

Fuzzyma
Fuzzyma

Reputation: 8474

svg.js v2.x

It is completely fine to use your own ids with svg.js. Just pass the id to the id method after you created your element:

canvas.rect(100, 200).id('myId')

You can later get that element by using SVG.get('myId') or SVG.select('#myId').first(). Make sure, that you set the id as soon as possible. They are important when linking pattern fills and gradients.

svg.js v3.x

Same as above but you now use SVG('#myId') to retrieve the element or SVG.find('#myId')[0]

Upvotes: 2

Related Questions