Reputation: 591
I'm making a template which users can change with their preferences. I'm working with SVGs within an object tag, all of these SVGs are icons and I need to set a hexadecimal color for all of them. If I plain put the svg in my html
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="35.482px" height="36.276px" viewBox="0 10.893 35.482 36.276" enable-background="new 0 10.893 35.482 36.276"
xml:space="preserve">
<g>
<path class="general-delete-btn" fill="#083847" d="M33.844,38.126l-7.222-7.221l-..."/>
</g>
</svg>
I could simple use a
$(".general-delete-btn").attr( "fill", "#000000" );
And thats it, I change them all, but SVGs get bigger an bigger in my project so I would like to do it with just the svg reference.
<object class='general-details-btn' data='general-details-btn.svg' type='image/svg+xml' height='20' width='20'>
How could I get the first result but by accessing the SVG within an object tag? Thanks for any guideline. Greetings
Upvotes: 1
Views: 93
Reputation: 123985
You need to get the document that the object element holds and then find the elements with that class in that document and finally call setAttribute on those elements. Something like this...
document.querySelectorAll(".general-details-btn").forEach(function(element, index, array) {
element.contentDocument.querySelectorAll(".general-delete-btn").forEach(function(element, index, array) {
element.setAttribute("fill", "#000000");
});
});
Upvotes: 1
Reputation: 591
I couldn't done it shorter but this did it with a double iteration and js, it works at least. Thanks for your help of course. Greetings.
var $objsLen = document.getElementsByTagName("object").length;
$i = 0;
for($i;$i<$objsLen;$i++){
var $obj = document.getElementsByTagName("object")[$i];
var $svgDoc = $obj.contentDocument;
var $patchesLen = $svgDoc.getElementsByTagName("path").length;
var $patches = $svgDoc.getElementsByClassName("general-details-btn");
$b = 0;
for($b;$b<$patchesLen;$b++){
$patches[$b].setAttribute("fill", "red");
}
}
Upvotes: 0