Reputation: 273
I'm looking for the proper method to define a series of variables using a jQuery each function rather than a traditional javascript for-loop.
topic1 = $('.selector-circle').children('.selector-1').text();
topic2 = $('.selector-circle').children('.selector-2').text();
topic3 = $('.selector-circle').children('.selector-2').text();
Originally, I wrote script like above, but now the project requires a varying number of "topics" and corresponding text(), so I need the code to be flexible rather than the more hard-coded method I first used.
I know how to slip in a variable in a .each for the '.selector-1' part, with "i" being the each index:
topic1 = $('.selector-circle').children('.selector-' + i).text();
But I don't know how to serialize the "topic1" variable name, so that it becomes essentially "topic + i" for however many times the each runs, and then that gets tied to each respective "selector + i".
Seems like I'm maybe needing an array to be created.
Thank you, in advance, for any and all helpful pointers.
Upvotes: 0
Views: 237
Reputation: 24638
An array would be far much better. And depending on what you want to do with the data you may not even need to do that. You want to use jQuery .filter()
and .map()
methods.
var topics = $('.selector-circle').children().filter(function () {
return this.className.match(/\bselector-\d+/);
}).map(function() {
return $(this).text();
}).get();
//result: ["topic1", "topic2", "topic3", ....]
Upvotes: 1
Reputation: 7266
You can simply use the wildcard
selection to select all your children. It is dynamic and you don't have to manage separate array to keep track of elements.
HTML
<div class="selector-circle">
<p class="selector-1 someother-class">selector 1</p>
<p class="selector-2">selector 2</p>
<p class="selector-3">selector 3</p>
<p class="selector-4">selector 4</p>
<p class="selector-5">selector 5</p>
</div>
JavaScript
var $selectors = $('.selector-circle').children('[class^="selector-"]');
$.each($selectors, function() {
var title = $(this).text();
console.log(title);
});
Output
selector 1
selector 2
selector 3
selector 4
selector 5
If in future you add selector-6
, selector-7
and so on, the above code will still run without need for change.
Here is the working jsfiddle.
Upvotes: 1
Reputation: 29846
One easy way is to use an array for that:
var arrOfData = [];
var length = 3; // change this if you need something dynamic
// fill the array
for(var i = 1 ; i <= length; i++)
{
arrOfData.push($('.selector-circle').children('.selector-' + i).text());
}
// Heres how you fetch data
function getTitle(idx){
return arrOfData[idx];
}
Upvotes: 0