Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS on SVG--getting innerHTML of an element

I wanted to extract some data from an SVG file. I know that SVG is XML, so I thought that it would be pretty easy to coax the data out with JS.

So, I wanted to get a bunch of text extracted from an SVG. So, I fired up chrome's JS console, and tried doing some stuff. I needed to get all the tspan elements in an array, extract their text, and categorize it.

I'm referring to http://upload.wikimedia.org/wikipedia/commons/e/eb/Light_spectrum.svg at the moment.

So, I use a = document.getElementsByTagName('tspan'). Now, I try a[20].innerHTML, and get undefined. Reasonable; it's not HTML and iirc innerHTML is nonstandard anyways.

Then I try a[20].childNodes[0] and get "ELF". OK, that's what I wanted. But, for some reason, this object is treated like a string, but can't be converted to one. If I try to convert it (so that I can use stuff like matches() and indexOf()), I get "[object Text]". Delving into Text.prototype doesn't help--I can't find any function that converts it to a string.

So how can one get the innerHTML of an SVG object through JS?

like image 748
Manishearth Avatar asked Mar 07 '12 13:03

Manishearth


2 Answers

Select the element like you have, but use the following to access its text:

var content = a[20].textContent;

This is no replacement for innerHTML inside SVG, but will work as long as you only want to extract text and no markup.

like image 123
Sirko Avatar answered Oct 12 '22 22:10

Sirko


A Text node looks like a string when you inspect it in the console, but it is not a string. For a string, you want the nodeValue. Try:

document.querySelectorAll('tspan')[20].childNodes[0].nodeValue
like image 45
Phrogz Avatar answered Oct 12 '22 22:10

Phrogz