0

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.

1
  • After you created the rect variable, why would you try to access it as a property on document? Commented Jan 2, 2015 at 19:16

3 Answers 3

2

You can simply do:

var rect = document.querySelectorAll(".1 rect");
for (var i = 0; i < rect.length; i++) {
    rect[i].style.fill="blue";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, much better to just put the additional query into the original selector and let the query engine do the work for you.
1

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";
    }
}

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.