Gabriel
Gabriel

Reputation: 5723

Trying to modify svg style with jquery

I loaded an svg file with and when trying to modify a style attribute with this:

$("object").contents().find('#path5431').css('fill', 'red');

I get nothing. The code is run after the svg is loaded. Any tips?

Thanks.

Edit:

<body>
     <object data='image.svg'></object>
</body>

Upvotes: 0

Views: 197

Answers (1)

rfornal
rfornal

Reputation: 5122

If the SVG is inline (embedded) into the html, editing it via CSS/Javascript is relatively simple.

However, when loaded from an external file, manipulation of the SVG structure is extremely difficult to say the least.

You might want to look into using something like an AJAX load to embed the SVG into the html, then manipulate ...

There are several issues with this approach (see How do I dynamically insert an SVG image into HTML?).

However, I've successfully used SVGInjector (see https://github.com/iconic/SVGInjector) to do things like:

<img id="image-one" class="inject-me" data-src="image-one.svg">
<img id="image-two" class="inject-me" data-src="image-two.svg">
// Elements to inject
var mySVGsToInject = document.querySelectorAll('img.inject-me');

// Options
var injectorOptions = {
  evalScripts: 'once',
  pngFallback: 'assets/png',
  each: function (svg) {
    // Callback after each SVG is injected
    console.log('SVG injected: ' + svg.getAttribute('id'));
  }
};

// Trigger the injection
SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
  // Callback after all SVGs are injected
  console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
});

I also ran into these articles recently ...

Upvotes: 1

Related Questions