Search code examples
javascriptcsssvgcss-animationssvg-animate

Why does CSS selector only style first matching svg path


I'm working with an inline SVG element that's made of two paths.

jsfiddle

HTML:

<svg class="flag" width="22px" height="22px" viewBox="0 0 22 22" version="1.1"
     xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
       <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
           <g>
              <path class="flag-path" d="M7.46666667,6.6875 L7.46666667,17 L6,17 L6,6.6875 C6,6.30780664 6.32832708,6 6.73333333,6 C7.13833958,6 7.46666667,6.30780664 7.46666667,6.6875 Z" fill="rgba(255,255,255,0.8)"></path>
              <path class="flag-path" d="M14.8,7.85094336 C15.6761729,7.85094336 16.4625125,7.40383203 17,7.065625 L17,13.4646387 C16.4625125,13.8028672 15.6761729,14.25 14.8,14.25 C13.9238271,14.25 13.1374875,14.0064746 12.6,13.6682461 C12.0625125,13.330082 11.2761729,13.0865566 10.4,13.0865566 C9.52382708,13.0865566 8.73751042,13.5045996 8.2,13.8427637 L8.2,7.44375 C8.73751042,7.10554297 9.52382708,6.6875 10.4,6.6875 C11.2761729,6.6875 12.0625125,6.93100391 12.6,7.26921094 C13.1374875,7.60741797 13.9238271,7.85094336 14.8,7.85094336 L14.8,7.85094336 L14.8,7.85094336 Z" fill="rgba(255,255,255,0.8)"></path>
           </g>
       </g>
</svg>

I've got some CSS and JS that's supposed to animate the color of the paths from white to green on click.

jsfiddle

.change-flag {
    animation: change-flag 750ms;
    fill: rgba(58,255,118,1);
}

@keyframes change-flag {
    from { fill: rgba(255,255,255,0.8) }
    to { fill: rgba(58,255,118,1); }
}

js jsfiddle

var flagCircle = document.querySelector('.el');
var flag = document.querySelector('.flag-path');
var anywhere = document.querySelector('html');

var highlightFlag = function () {
    flagCircle.classList.toggle('change-circle');
    flag.classList.toggle('change-flag');
};

anywhere.addEventListener('click', highlightFlag, false);

When the event is triggered and the animation executed, only one of the paths turns green. What's going on here?


Solution

  • document.querySelector only returns one (the first) element matched by the given selector. Use document.querySelectorAll instead

    var flagCircle = document.querySelector('.el');
    var paths = document.querySelectorAll('.flag-path');
    //...
    
    var highlightFlag = function () {
        //...
        for (var i = 0, l = paths.length; i < l; i++) {
            paths[i].classList.toggle("change-flag");
        }
    };
    

    http://jsfiddle.net/pdpqg74t/