7

I have the following js script to access elements inside a object (SVG - <object data="bbbbbb.svg" type="image/svg+xml" id="alphasvg" width="100%" height="100%"></object> )

jQuery(document).ready(function($) {

    $(window).load(function () {


        var a = document.getElementById("alphasvg");
        var svgDoc = a.contentDocument; 
        var delta = svgDoc.getElementsByTagName("path");    
        $(delta).click(function() {

            //do stuff

        })

    });
});

I want to use jQuery to access the elements and tags. I'm completely stuck on the contentDocument part. How can I convert this to jQuery so I can use attr etc?

I want to be able to access and modify attributes in jQuery instead of having to use the traditional js methods which I am unfamiliar with.

How someone can help me?

Thanks a million.

ppeterka
  • 20,583
  • 6
  • 63
  • 78
user752135
  • 71
  • 1
  • 1
  • 2

3 Answers3

5

You should be able to access the paths directly like elements, no need for contentDocument or getElementsByTagName, etc:

jQuery(document).ready(function($) {

    $(window).load(function () {

        $("#alphasvg path").click(function() {

            //do stuff
            // $(this).attr('d') = the path

        })

    });
});
Gary Green
  • 22,045
  • 6
  • 49
  • 75
5

Like this:

$(svgDoc).find("whatever").doWhatever();

Demo here and code here. Note that I've used an <iframe> for demonstration hence the first URL will work, second will give you "permission denied" error if you try to run the fiddle.

Salman A
  • 262,204
  • 82
  • 430
  • 521
  • I was still getting same origin issues (http://stackoverflow.com/questions/2753732/how-to-access-svg-elements-with-javascript/3379830#comment25937521_3379830) when I ran without a server, so use a server, even for just client-side js and html as in these examples. – Michael Jul 22 '13 at 07:37
2

If you are embedding SVG into HTML using the object tag (as opposed to inline SVG), this then this is a duplicate of a previous question, the answer to which may be found here: How to access SVG elements with Javascript

Community
  • 1
  • 1
jbeard4
  • 12,664
  • 4
  • 57
  • 67