Himmators
Himmators

Reputation: 15016

Special case for first item when looping through array and getting previous value?

I'm currently doing this, to store the height of each item to later access it via css:

children[0].style.setProperty('--previousHeight', 0+'px');
children.forEach((child, i) => {
    if(i > 0 ){
        var height = children[i-1].offsetHeight;
        child.style.setProperty('--previousHeight', height+'px');
    }
})

I would like to treat the first item more like the other once. Something like

height = offsetHeight || 0;

But i'm not sure how I can do it in a easy to read way

Upvotes: 0

Views: 70

Answers (3)

Himmators
Himmators

Reputation: 15016

This is what I ended up doing:

    children.forEach((child, i) => {
        var height = 0 
        if(i > 0 ){
            var height = children[i-1].offsetHeight;
        }
        child.style.setProperty('--previousHeight', height+'px');
    })

Upvotes: 0

BRO_THOM
BRO_THOM

Reputation: 851

This should be the quickest and cleanest way.

<div id='myElement'>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</diV>
<script>
    var children = document.getElementById('myElement').children;
    var h = children[0].offsetHeight;
    for(var i in children){
        if( i > 0 ){
            children[i].style['height'] = h;
            children[i].style.setProperty('--previousHeight', h);                
        }            
    }
</script>

Upvotes: 0

Faly
Faly

Reputation: 13356

It should be:

children.forEach((child, i) => {
    var height = children[i-1] && children[i-1].offsetHeight || 0;
    child.style.setProperty('--previousHeight', height+'px');
})

If you're not familiar with:

var height = children[i-1] && children[i-1].offsetHeight || 0;

It gives the same result as:

var height = children[i-1] ? children[i-1].offsetHeight : 0;

Upvotes: 2

Related Questions