John the User
John the User

Reputation: 640

How to get elements with same class from two separate arrays with one call?

I have a situation as follows:

<div class="milk">
    <span class="onion">1</span>
</div>
<div class="milk">
    <span class="onion">2</span>
</div>
<div class="milk">
    <span class="onion">3</span>
</div>

<div class="stone">
    <span class="onion">1</span>
</div>

<div class="stone">
    <span class="onion">2</span>
</div>

<script>
    var onions = [];
    var milk = [].slice.call( document.querySelectorAll( '.milk' ));
    var stone = [].slice.call( document.querySelectorAll( '.stone' ));

    milk.forEach( function( element, i ) {
        onions.push(element.querySelector( '.onion' ));
    });

    stone.forEach( function( element, i ) {
        onions.push(element.querySelector( '.onion' ));
    });
</script>

As you can see, I use a similar same statement to push .onion elements from the milk and stone elements. And here lies my question — out of curiosity, is there a way to push onion elements into array onions with one line or statement, without merging the two arrays first?

Assuming the following statement was valid (it's not), this is the kind of answer I'm looking for:

(stone, milk).forEach( function( element, i ) {
        onions.push(element.querySelector( '.onion' ));
    });

Upvotes: 0

Views: 55

Answers (1)

trincot
trincot

Reputation: 350770

If your question is how to traverse two arrays with one call, then consider concat:

milk.concat(stone).forEach( /* callback */ )

Or with ES6 spread syntax:

[...milk, ...stone].forEach( /* callback */ )

If the reason for using forEach is to build a new array (onions), then consider using map instead:

onions = milk.concat(stone).map(function (elem) { 
    return elem.querySelector('.onion');
});

But for your particular query, you would better put the logic in the CSS selector using querySelectorAll(), which Ori Drori had proposed in his deleted answer:

onions = Array.from(document.querySelectorAll('.milk > .onion, .stone > .onion'));

Upvotes: 1

Related Questions