Raphael.js: Get Value Of A Text Node
October 13, 2011 Leave a Comment
When using the Raphael.js library for SVG manipulation, setting the text of a text element is as easy as
var paper = Raphael(10, 50, 320, 200);
var textEl = paper.text("My Text", 0, 0); // create a new element
// and later if we want to update the text
textEl.attr('text', 'My New Text');
However, getting the current text in this node is not as straight forward. The library dictates you should do something similar to var currentText = textEl.attr('text');, but logging that to the console outputs an Object and not a String. I’ve searched the net for months for the answer to this, and the solution I finally came up with today, after inspecting the DOM and seeing the elements being returned, is as simple as
var currentText = textEl[0].attr['text'];
The reason it needs to be this way is because the library treats the text node as a “Set” of two text elements instead of a simple HTML Element with inner text. I hope I’ve helped someone today. Happy JS Development, y’all.