SVG上的JS-获取元素的innerHTML [英] JS on SVG--getting innerHTML of an element
问题描述
我想从SVG文件中提取一些数据.我知道SVG是XML,所以我认为使用JS哄骗数据非常容易.
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.
因此,我想从SVG中提取一堆文本.因此,我启动了chrome的JS控制台,并尝试做一些事情.我需要获取数组中的所有tspan
元素,提取其文本,然后进行分类.
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.
我指的是 http://upload.wikimedia.org/wikipedia/commons/e/eb/Light_spectrum.svg .
因此,我使用a = document.getElementsByTagName('tspan')
.现在,我尝试a[20].innerHTML
,并得到undefined
.合理的;它不是HTML,而且iirc innerHTML仍然是非标准的.
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.
然后我尝试a[20].childNodes[0]
并获得"ELF"
.好,那是我想要的.但是,由于某种原因,该对象被视为字符串,但是无法转换为一个.如果我尝试将其转换(以便可以使用matches()
和indexOf()
之类的东西),则会得到"[object Text]"
.深入研究Text.prototype
没有帮助-我找不到任何将其转换为字符串的函数.
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.
那么如何通过JS获取SVG对象的innerHTML?
So how can one get the innerHTML of an SVG object through JS?
推荐答案
根据需要选择元素,但是使用以下内容访问其文本:
Select the element like you have, but use the following to access its text:
var content = a[20].textContent;
这不能替代SVG中的innerHTML
,但是只要您只想提取文本且没有标记,就可以使用.
This is no replacement for innerHTML
inside SVG, but will work as long as you only want to extract text and no markup.
这篇关于SVG上的JS-获取元素的innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!