简体   繁体   中英

How to iterate on a group's elements/children in snap.svg?

Let's say I have an svg group of type <g> called "group1" that has a number of children (other shapes, etc). I'd like to iterate on them using snap.svg.

var group1 = s.select('#group1');
group1.forEach(function(child) {

   // doesn't work

});

any ideas?

You can find the Snap doc for forEach here

Firstly, you need to use s.selectAll instead of s.select here.

var set = s.selectAll

Select will choose the first element, selectAll will choose all of the elements that match the css selector and put them in a Set, so you can then use your forEach.

Then you can iterate over them, similar to what your example. So I would use the '*' selector to get the children for example.

s.selectAll('#group1 *')
 .forEach( function( el ) {
    el.attr({ fill: 'blue' });
});

If you don't specifically need the forEach, as you just want to set some attributes to them, you can possibly avoid it, as some methods can be applied to sets. So the above example could also be written like...

s.selectAll('#group1 *').attr({ fill: 'red' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM