0

Looping through children elements using each.

var divHeights = [];  
$('#parent').children('div').each(function () {  
     divHeights.push(this.clientHeight);    
});  
alert(divHeights);  // fails

How can I return the divHeights variable?

I've tried
var hts = ('#parent').children('div').each(function () { ...
but obviously that won't work.

7
  • divHeights should contain them after the .each statement. So just use it afterwards. Commented Aug 24, 2015 at 16:35
  • 1
    return divHeights; after the loop. What's not working about that? Commented Aug 24, 2015 at 16:35
  • 3
    where in your code are you failing to access divHeights? When I run it, divHeights gets filled in as expected Commented Aug 24, 2015 at 16:36
  • You are already adding the heights to the array. You have access to all of the heights at that point. Commented Aug 24, 2015 at 16:36
  • updated to show variable access & where it fails Commented Aug 24, 2015 at 16:40

3 Answers 3

3

You can do this in better way using .map() like:-

var divHeights = $('#parent').children('div').map(function () {
    return this.clientHeight || 0;
}).get();

DEMO FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

1

The divHeights variable is available all the time. You can just assign it to a variable whenever you want:

var hts = divHeights;

This will just be another reference to the array, so you can do that any time after the array is created, even before you have put any values into it:

var divHeights = [];  
var hts = divHeights;
$('#parent').children('div').each(function () {  
  divHeights.push(this.clientHeight);    
});

You can of couse just use the variable divHeights instead of the variable hts when you want to use the result, or just use the variable hts instead of divHeights from start.

Comments

0

You could make it into a function like this:

function getHeights() {
    return $('#parent div').map(function() {
        return this.clientHeight;
    });
}

Then you can just call the function wherever you like to get the array contents.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.