urschrei
urschrei

Reputation: 26859

Get first child of the first child of each element in an array

I've built an array of table elements matching a specific criterion using querySelectorAll(), but I'd like to conditionally create a new, separate array containing the first child of the first child of each of those elements.
However, I'm not sure how to do this. My array currently looks like this:

var arr = [
    <table class="matchedCriterion">…</table>,
    <table class="matchedCriterion">…</table>
];

Is there a way for me to run querySelector() or querySelectorAll() on each element, matching what I want using :first-child:first-child

Upvotes: 0

Views: 2529

Answers (1)

I Hate Lazy
I Hate Lazy

Reputation: 48761

The .map function lets you build a new Array from another array.

var newarr = arr.map(function(el) { return el.firstChild.firstChild; });

If your arr is not actually an array, then do this.

var newarr = [].map.call(arr, function(el) { return el.firstChild.firstChild; });

Be aware that this will get text nodes if those happen to be the first child. If you want elements only, use .firstElementChild instead of .firstChild.

Upvotes: 4

Related Questions