JavaScript concat document.querySelectorAll

Merge two lists of elements returned by document.querySelectorAll().

Given the following html, select the div and list items.

var someNode = document.querySelector('div');
var moreNodes = document.querySelectorAll('li');
var combined = [someNode].concat(;
console.assert(combined.length === 4);

The combined variable now contains [div, li, li, li].

Here is a real-world example where comments of a thread are obtained by specifying a target element.

A list of nested comments with one "current" comment.

<div class="comment">
    comment 1
    <div class="comment">
        comment 2
        <div class="comment">
            comment 3
    <div class="comment">
        comment 4
<div class="comment current">
    comment 5
    <div class="comment">
        comment 6
    <div class="comment">
        comment 7
        <div class="comment">
            comment 8
        <div class="comment">
            comment 9
<div class="comment">
    comment 10

Obtain the list of comments from the "current" target thread.

function getCommentsFromThread(targetNode) {
    var childNodes = targetNode.querySelectorAll('.comment');
    var targetAndChildNodes = [targetNode].concat(;
    var comments = [];
    targetAndChildNodes.forEach(function(element) {
    return comments;

var target = document.querySelector('.current');
var threadComments = getCommentsFromThread(target);

var expected = [
    'comment 5',
    'comment 6',
    'comment 7',
    'comment 8',
    'comment 9',
console.assert(JSON.stringify(expected) === JSON.stringify(threadComments));


  1. anonymous

    Wouldn't this be the same as document.querySelector('div, li')?

    1. anonymous

      I've added another example.

Leave a Reply