I’m having difficulties in accessing an ID that is inside an SVG file and inside of a rect
tag, to manipulate the SVG’s I’m using the Snap.svg library. In this case I want to get the get the id="rect252"
in javacript file and change the visibility of this object. For some reason I’m not able to get this ID.
My HTML:
JavaScript
x
3
1
<svg id="main"></svg>
2
<button onclick="changeSvg('rect252')">Change</a>
3
My Javascript:
To place an image with Snap library
JavaScript
1
2
1
let m = Snap('#main').image("image.svg", 0, 0, 500, 500)
2
Function
JavaScript
1
12
12
1
function changeSvg(id){
2
let svgTag = document.getElementById('main')
3
svgTag.addEventListener("load", function(){
4
let svgDoc = svgTag.contentDocument;
5
let getID = svgDoc.getElementById(id);
6
7
Snap('#' + getID).attr({
8
visibility: 'visible'
9
})
10
})
11
}
12
SVG Structure:
JavaScript
1
16
16
1
<g
2
id="g327"
3
inkscape:label="Top Center"
4
transform="translate(-3.3026586,-12.907715)"
5
style="display:block">
6
<rect
7
style="display:inline;fill:#000000"
8
id="rect252"
9
width="51.396542"
10
height="31.275505"
11
x="120.8588"
12
y="92.630028"
13
inkscape:label="Right"
14
visibility="hidden" />
15
</g>
16
If anyone has any suggestions I would appreciate it, thanks
Advertisement
Answer
You can’t access the id for an svg image.
However, you can if you use an object tag instead.
JavaScript
1
2
1
<object id="main" data="image.svg" width="600" height="600" type="image/svg+xml"></object>
2
Then you can use contentDocument to access it. Example.
JavaScript
1
4
1
var tux = Snap("#main");
2
var tuxContent = tux.node.contentDocument; /// grab the referenced content
3
4