Relm
Relm

Reputation: 8262

How to create elements inside a loop and store them into a variable in JavaScript to be accessed outside the loop

I want to create some elements of a particular number, inside a loop, store them in a variable, then access that variable outside that loop.

The reason I want to access that variable outside the loop is so that I can put them inside an append function.

function range(start, stop, step) {
    var a = [start],
        b = start;
    while (b < stop) {
        b += step;
        a.push(b);
    }
    return a;
}
var yAxis = range(1, 100, 10);

$.createAxis = function(axisValues) {
    $(axisValues).each(function(index, element) {
        yAxisNav = document.createElement('div');
        var newValue = document.createTextNode("I have content!");
        yAxisNav.appendChild(newValue);
        return yAxisNav.className = 'graphBar_yAxis_label';
    });
}(yAxis);

console.log(yAxisNav);
//$('body').append('<section>'+yAxisNav+'</section>');

The above only returns one element, how can I store this so that its accessible outside that loop?

Upvotes: 0

Views: 90

Answers (3)

Kiran Ramchandra Parab
Kiran Ramchandra Parab

Reputation: 506

As you wants to return a list of div's, I have moved yAxisNav outside function and appending it with every loop.

I think you are looking for this...

var yAxisNav = "";
$.createAxis = function (axisValues) {
    $(axisValues).each(function (index, element) {
        var elem;
        elem = document.createElement('div');
        var newValue = document.createTextNode("I have content!");
        elem.appendChild(newValue);
        elem.className = 'graphBar_yAxis_label';
        yAxisNav += elem.outerHTML;
    });
    return yAxisNav;
}(yAxis);

console.log(yAxisNav);
$('body').append('<section>'+yAxisNav+'</section>');

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Get the value returned by createAxis

return yAxisNav object from the function. This should be the last statement in the function createAxis,

return yAxisNav;

And then you can get it as follow:

var yAxisNav = $.createAxis(something);

CODE

$.createAxis = function(axisValues) {
    $(axisValues).each(function(index, element) {
        yAxisNav = document.createElement('div');
        var newValue = document.createTextNode("I have content!");
        yAxisNav.appendChild(newValue);
        yAxisNav.className = 'graphBar_yAxis_label'; // Move up
        return yAxisNav; // Return complete object
        // ^^^^^^^^^^^^^
    });
}(yAxis);

Upvotes: 1

JBux
JBux

Reputation: 1394

As mentioned here, define the variable in the highest scope in which you want to access it.

In this case, define it outside the range function.

Upvotes: 0

Related Questions