Reputation: 13843
I need to iterate over multiple path containers <g>
, and add a unique class to each one, then for each of the paths inside the container I need to add a unique class.
This is my output:
<svg>
<g>
<path class="active" fill="#1f77b4" d="M1.0715305595945801e-14,-175A175,175 0 0,1 151.55444566227678,87.49999999999997L138.5640646055102,79.99999999999997A160,160 0 0,0 9.796850830579018e-15,-160Z"></path>
<path class="active" fill="#aec7e8" d="M151.55444566227678,87.49999999999997A175,175 0 0,1 -151.55444566227675,87.50000000000006L-138.56406460551017,80.00000000000006A160,160 0 0,0 138.5640646055102,79.99999999999997Z"></path>
<path class="active" fill="#ff7f0e" d="M-151.55444566227675,87.50000000000006A175,175 0 0,1 -3.21459167878374e-14,-175L-2.9390552491737054e-14,-160A160,160 0 0,0 -138.56406460551017,80.00000000000006Z"></path>
</g>
<g>
<path class="active" fill="#1f77b4" d="M1.0715305595945801e-14,-175A175,175 0 0,1 151.55444566227678,87.49999999999997L138.5640646055102,79.99999999999997A160,160 0 0,0 9.796850830579018e-15,-160Z"></path>
<path class="active" fill="#aec7e8" d="M151.55444566227678,87.49999999999997A175,175 0 0,1 -151.55444566227675,87.50000000000006L-138.56406460551017,80.00000000000006A160,160 0 0,0 138.5640646055102,79.99999999999997Z"></path>
<path class="active" fill="#ff7f0e" d="M-151.55444566227675,87.50000000000006A175,175 0 0,1 -3.21459167878374e-14,-175L-2.9390552491737054e-14,-160A160,160 0 0,0 -138.56406460551017,80.00000000000006Z"></path>
</g>
</svg>
I can do the following:
$.each(path, function(i,elem) {
$(elem).parent('g').attr('class','active' + i);
});
Upvotes: 1
Views: 1200
Reputation: 4495
Tested Code: jsfiddle
$("g").each(function(i,elem)
{
$(elem).attr('class','class'+i);
$(elem).find("path").each(function(i,child)
{
$(child).attr('class','class'+i);
});
});
Upvotes: 1
Reputation: 11371
You're trying to use $.each
. This will work for arrays []. According to docs,
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
For DOM elements, you need to use $("selector").each()
. According to docs,
Iterate over a jQuery object, executing a function for each matched element.
And more :
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object.
So, you have to do it this way :
$("path").each( function(i) {
$(this).attr("class","yourClass").parent('g').attr('class','active' + i);
});
To access the current element, you need to use $(this)
.
Upvotes: 1