2

I have 4 charts each with their own divs in html. I'm trying to find the best way to add these charts to an array automatrically without having to update the array whenever I make a change to the charts and their ID's.

HTML:

<table id="dashboard" cellpadding="0" cellspacing="0">
    <tr>
        <td id="c1"><div class='chartLoadingOverlay'>Loading chart please be patient...</div></td>
        <td id="c2"><div class='chartLoadingOverlay'>Loading chart please be patient...</div></td>

    </tr>
    <tr>
        <td id="c3"><div class='chartLoadingOverlay'>Loading chart please be patient...</div></td>
        <td id="c4"><div class='chartLoadingOverlay'>Loading chart please be patient...</div></td>
        <!--<td id="BottomRight"><div class='chartLoadingOverlay'>Loading chart please be patient...</div></td>-->
    </tr>   
</table>

JS:

var arrOfChartContainers = ["c1","c2","c3","c4"];  <-- I want to automate this
2
  • An array is just a dumb data structure; it can’t update itself. I think what you really want is a method getChartContainers() that returns an array of the current chart containers. Would that be okay? Sep 13, 2013 at 16:31
  • What ever works really
    – Batman
    Sep 13, 2013 at 17:04

2 Answers 2

3

DEMO

var x = $('.chartLoadingOverlay').closest('td').map(function () {
    return this.id;
}).get();
console.log(x);

.map()

1
  • You should use .get() method, .map() returns a jQuery-wrapped array.
    – Ram
    Sep 13, 2013 at 16:31
1

@Tushar Gupta has a great answer. Here's my 2 pennies worth though just in case.

var arrOfChartContainers = [];
$('table td').each(function() {
    arrOfChartContainers.push(this.id);
});
console.log(arrOfChartContainers);

Fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.