Reputation: 8262
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
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
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