14

I'm using Snap.svg to load an SVG image and add text elements to it. However, I need to be able to update the text elements as the page loads.

Right now, I'm doing something like this:

var svg = Snap("#selector");
var text;
Snap.load(path_to_file, function(f) {
    svg.append(f);
    var g = svg.select("g");
    text = g.text(x_pos, y_pos, label);
}

Let's say I want to update the text later, how do I do this? I am guaranteed to update the text object after it's been created after calling load.

The only way I've managed to modify the text is by setting an id to the element and then doing it with jQuery like this:

self.selector.find("#my_id")[0].textContent = "New text";

However, this feels really wrong and I think I might just be missing something with the Snap API.

Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
Andrew Hassan
  • 591
  • 2
  • 5
  • 15

3 Answers3

27

I think it should be as simple as

text.attr({ text: 'my new text'});

so

setTimeout( function() { text.attr({ text: 'my new text'}) }, 2000 );

would test it

Ian
  • 13,724
  • 4
  • 52
  • 75
  • 1
    This does not work for me. However, if I do `text.attr({"#text", "my new text"});`, then it works. – djip.co Dec 29 '16 at 16:20
  • This doesn't sound right and sounds like a bug. Maybe post up a jsfiddle if you want to double check it. – Ian Dec 30 '16 at 10:21
  • @Djip The `'text'` var in your example may in-fact be a `tspan` element. Calling `text.parent().attr({text: "new Text'})` will just replace the whole tspan (attributes and all) with raw text, so that's not necessarily great either, but will confirm what's happening. – Dave E Oct 01 '17 at 12:17
4

Another way, you can directly get a reference of DOM node using Element.node, so you can mess around

text.node.textContent = "New text";
text.node.innerHTML = "New text";
text.node.innerHTML = 'a<tspan dy="5">2</tspan>'
malcomwu
  • 157
  • 1
  • 9
0

With jquery

$(s.select('#id').node).text('new text');
Lukasz Frankowski
  • 2,955
  • 1
  • 31
  • 32
  • 6
    A sentence or two of explanation goes a long way towards making a possibly correct answer into a great one. –  Jan 10 '15 at 00:51