简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM