0

In a page that contains an SVG image as an object, we can address individual elements by ID (How to access SVG elements with Javascript):

<object data="myimage.svg" type="image/svg+xml" id="alphasvg"></object>
<script>
    var a = document.getElementById("alphasvg");
    a.addEventListener("load", function () {
        var svgDoc = a.contentDocument; //get the inner DOM of alpha.svg
        var delta = svgDoc.getElementById("myelement"); //get the inner element by id

        delta.addEventListener("mousedown", function () { alert('hello World!') }, false);    //add behaviour
    }, false);
</script>

But using svgDoc.getElementById("mygroupelement") to reference a group element by its ID does not work.

<svg ...>
<path id = "myelement" ...>
<g id="mygroupelement" ...> <.. various path/polyline/etc elements..> </g>
</svg>

So how do you reference a group element in an SVG?

(See also How to get an SVG(+XML) image to interact with the page it is in, where the interaction is in the other direction - from the element to the page.)

Community
  • 1
  • 1
htchmn
  • 13
  • 8
  • 1
    what do you mean with 'does not work'? svgDoc.getElementById("mygroupelement") return undefined? – ale Dec 22 '14 at 18:12
  • It should work. Please post the exact code you're using that doesn't work, with what you expect to happen. It may simply be that something else isn't working the way you expect. – AmeliaBR Dec 22 '14 at 21:30
  • For example, this works where 'myelement' is the ID of an element inside or outside a group, but not when it is the ID of the group itself: function changeColor(color) { var path = document.getElementById("alphasvg").getSVGDocument().getElementById("myelement"); path.style.setProperty("fill", color, ""); } – htchmn Dec 22 '14 at 22:53
  • the function here returns [object SVGGEelement]. Presumably we need to select each element within the group to act on. How? – htchmn Dec 23 '14 at 09:07
  • Problem solved. Not a referencing problem. Attributes of a group are subordinate to attributes of the elements within the group. So changing the fill attribute of the group has no effect if the elements within the group have their fill attribute set. – htchmn Dec 23 '14 at 10:56

0 Answers0