JS on SVG--getting innerHTML of an element
Asked Answered
F

2

8

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?

February answered 7/3, 2012 at 13:50 Comment(1)
Also, for some reason, the prototype shows that certain other built in functions that one normally sees in HTML (in fact, exactly the ones which I need) are all missing. Great--now the W3C is conspiring against me...February
R
9

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.

Romy answered 7/3, 2012 at 13:53 Comment(2)
what significance is index 20, by the way? This index value would never hypothetically be any other number I assume?Orff
@NateNeuhaus The 20 is just referring to OPs code given. Here the 20th <tspan> element should be selected. Can be any other. Main aspect is the property (textContent) to use afterwards.Romy
B
2

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
Bighead answered 7/3, 2012 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.