Reputation: 81
In the following code, using jquery's each() and html() inserts only the first div value i.e. "David Smith" in the whole array (all_names[]) wheres I expected each() to iterate over each div and insert their corresponding value into corresponding array index.
More than code correction, I prefer if anybody can tell me the reason behind such behavior of each() or html() function (I'm not sure). I am a beginner in jQuery and this will help me strengthen my understanding of jquery.
Thanks dkj
HTML
<div class="test"><a href="#">David Smith</a></div>
<div class="test"><a href="#">Adam John </a></div>
<div class="test"><a href="#">Tina Samara </a></div>
<div class="test"><a href="#">James White </a></div>
JQUERY
<script type="text/javascript">
var all_names = [];
var total_names = $('div.test a');
total_names.each(
function() {
all_names[counter] = total_names.html();
counter++;
}
);
alert("total Names: " + all_names);
</script>
Upvotes: 0
Views: 72
Reputation: 4066
Use second argument of each function to achieve item
<script type="text/javascript">
var all_names = [];
var total_names = $('div.test a');
total_names.each(
function(index, item) {
all_names[counter] = $(item).html();
counter++;
}
);
alert("total Names: " + all_names);
</script>
Upvotes: 1
Reputation: 15361
You are missing the point of each
. It iterates over array giving the current element in the array to its callback function as the second argument (first being the current index). Instead of calling html
on the current element in the loop, you always call it on the entire matched list.
<script type="text/javascript">
var all_names = [];
var total_names = $('div.test a');
total_names.each(
function(idx, elemInArray) {
all_names[counter] = $(elemInArray).html();
counter++;
}
);
alert("total Names: " + all_names);
</script>
Also worth to note that in iterations of each, this
is a reference to the current item. It can simplify accessing items like so
$(someArrayOfElements).each(function() {
console.log($(this).html()); // $(this) is the current item wrapped into a jQuery object
});
Upvotes: 3
Reputation: 782508
Use .map()
instead of .each()
var all_names = total_names.map(function() {
return $(this).html();
}).get();
.get()
is needed at the end to convert the jQuery collection that .map()
returns to an ordinary array.
Upvotes: 1