Mikkel Rev
Mikkel Rev

Reputation: 901

Change the fill of all elements inside an svg using javascript

I would like to change the fill color of all elements inside an SVG. The elements are both type rect and polygon. I have not set a default color.

Here is a sample file:

http://www.kingoslo.com/instruments/test.svg

How can I do this most elegantly?

Upvotes: 0

Views: 6776

Answers (3)

manyu
manyu

Reputation: 101

This worked for me while working with a complex SVG having a lot of nested elements:

$('svg').find('path, text').css('fill', '#ffffff')

Upvotes: 1

Erik Dahlström
Erik Dahlström

Reputation: 60966

Another variant similar to the one by Robert Longson:

document.documentElement.style.fill = 'blue';

I prefer documentElement over rootElement because it's in DOM Core, and they're mostly the same.

Upvotes: 1

Vinay
Vinay

Reputation: 6322

If you have jQuery:

$('svg').children().css('fill', '#ffffff');

EDIT: Note that this assumes the rects and polygons are the direct children of the svg element.

Upvotes: 4

Related Questions