Reputation: 263
I have a svg script with a few rects:
<g class="1">
<rect x="80.181" y="156.8" width="64.394" height="54.973"/>
</g>
<g class="2">
<rect x="147.067" y="156.8" width="23.89" height="54.973"/>
</g>
<g class="1">
<rect x="173.45" y="156.8" width="22.433" height="54.973"/>
</g>
<g class="3">
<rect x="198.375" y="156.8" width="39.668" height="54.973"/>
</g>
(...)
And I want to create a function that defines the fill of all rects inside class, for example, 1. Something like:
function FillRect() {
var rect = document.getElementsByClassName('1');
for (var i = 0; i < rect.length; i++) {
document.rect[i].querySelector('rect').style.fill="blue";
}
}
I'm not sure how to do the last document.rect[i].querySelector
part.
Upvotes: 0
Views: 664
Reputation: 766
function FillRect() { var rect = document.getElementsByClassName('1');
for (var i = 0; i < rect.length; i++) {
rect[i].getElementsByTagName('rect').style.fill="blue";
}}
This should do what you want. You may consider jQuery if you want.
Upvotes: 0
Reputation: 64
You don't need refer to the document object.
function FillRect() {
var rect = document.getElementsByClassName('1');
for (var i = 0; i < rect.length; i++) {
rect[i].querySelector('rect').style.fill="blue";
}
}
Upvotes: 1
Reputation: 104775
You can simply do:
var rect = document.querySelectorAll(".1 rect");
for (var i = 0; i < rect.length; i++) {
rect[i].style.fill="blue";
}
Upvotes: 2