I’m trying to get multiple attributes from unordered lists from multiple divs that look like this:
<div class="graph" style="display:none;">
<ul g-max='10'>
<li g-color='green' g-val='4'></li>
<li g-color='blue' g-val='3.6'></li>
<li g-color='red' g-val='8'></li>
</ul>
</div>
<div class="graph" style="display:none;">
<ul g-max='14'>
<li g-color='green' g-val='2'></li>
<li g-color='blue' g-val='9'></li>
<li g-color='red' g-val='3.98'></li>
</ul>
</div>
I’m trying to do this with jQuery and I’m using the following:
var graph_array = [];
$('.graph').each(function(divind)
{
$('ul').each(function(ulind)
{
$('li').each(function(liind)
{
graph_array[divind][ulind][liind]['g-val'] = $(this).attr('g-val');
graph_array[divind][ulind][liind]['g-color'] = $(this).attr('g-color');
});
});
});
alert(graph_array);
But, even when I move things around and try different techniques like .map() or .toArray(), nothing works. Any ideas? Thanks in advance!
EDIT: I’m wanting to have an ending result that’ll look like this:
[{
{
{g-color:green, g-val:4},{g-color:blue, g-val:3.6},{g-color:red, g-val:8}
},
{
{g-color:green, g-val:2},{g-color:blue, g-val:9},{g-color:red, g-val:3.98}
}
}]
The main thing to look out for here is that you did not initialize the arrays you were trying to append to. You’ll need to initialize an array for each group.
Another thing to do here is utilize the scope of the
eachfunction and one of its two parameters.I’ve listed two interchangeable ways you can use the scope of the
eachand also utilize thethiskeyword. When you are in each iteration of theeachloop, the current item can be found in the$(this)variable. You could also use$(elem).In cases where you have nested
eachcommands, I find it better to use a different variable for each nested loop and not usethis. I find it less confusing.So basically what you need to do is use the relative current variable to search within its decedents.
Live Demo