Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select SVG width using jQuery?

I need to be able to select the width and height of an svg element inside an embed element using jQuery. Note that it has to be inside an embed element, if that matters to the answer.

I tried this as a test but it returns undefined:

var width = $('embed:first').children("svg:first").attr("width");
alert(width);

Later when I get this to work I'm going to use .each, so this is just for testing.

Some googling seems to suggest that svg cannot be so easily selected this way. Can someone explain exactly how to do it instead? If I need to use the jQuery SVG plugin, can you explain the usage to achieve the above, because I couldn't get that from the examples on the site.

UPDATE: Please note that the svg is embedded in an embed element with the src attribute:

<embed class="image" width="100%" height="100%"
               src="svgimage.svg"
                        ></embed>
like image 477
Anders Avatar asked Jan 24 '26 11:01

Anders


1 Answers

Just download jquery.svg.js and load it with a script element after jQuery:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src='/js/jquery.svg.js'></script>

To get hold of the SVG element:

var svg   = document.querySelector('embed').getSVGDocument().documentElement;
var width = svg.getAttributeNS(null, 'width');
console.log(width);

To get hold of all embed, use document.querySelectorAll('embed') instead.

Full example (must be run on server/localhost, local file wont work):

<!doctype html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src='jquery.svg.js'></script>
  </head>
  <body>
    <embed src="circle1.svg" type="image/svg+xml">
    <embed src="circle2.svg" type="image/svg+xml">

    <script>
      (function () {
        var embeds, embed, i, onSvgLoaded;

        onSvgLoaded = function () {
          var $svg;

          $svg  = $( this.getSVGDocument().documentElement );
          width = $svg.attr('width');
          console.log('Width:', width);
        };

        embeds = document.querySelectorAll('embed');

        for (i=0; embed=embeds[i]; i++) {
          embed.addEventListener('load', onSvgLoaded);
        }

      })();
    </script>
  </body>
</html>

circle1.svg:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100" height="100">
  <circle cx="50" cy="50" r="50" fill="red"/>
</svg>

circle2.svg:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="200" height="200">
  <circle cx="100" cy="100" r="100" fill="red"/>
</svg>
like image 155
bennedich Avatar answered Jan 25 '26 23:01

bennedich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!