Search code examples
javascriptappendchild

How to append all elements of a certain class to the DOM


I'd like to append all elements of the class 'active_element' to the document.body

How do I achieve this:

var element1 = document.createElement('div');
element1.classList.add('active_element');

var element2 = document.createElement('div');
element2.classList.add('active_element');

document.body.appendChild(element1);
document.body.appendChild(element2);

With a loop:

var element1 = document.createElement('div');
element1.classList.add('active_element');

var element2 = document.createElement('div');
element2.classList.add('active_element');

var active_elements = document.getElementsByClassName('active_element');
for (i=0; i<active_elements.length; i++) {
    document.documentElement.appendChild(active_elements[i]);
} // doesn't seem to work

Solution

  • You can't find the elements with document.getElementsByClassName() until after they're added to the DOM.

    Just use a loop to add them to the DOM, instead of assigning them to variables.

    const divCount = 2;
    for (i = 0; i < divCount; i++) {
        var element = document.createElement('div');
        element.classList.add('active_element');
        document.documentElement.appendChild(element);
    }
    

    If you need to create the DIVs at a separate time from when you append them, you could put them into an array.

    active_elements = [];
    var element1 = document.createElement('div');
    element1.classList.add('active_element');
    active_elements.push(element1);
    
    var element2 = document.createElement('div');
    element2.classList.add('active_element');
    active_elements.push(element2);
    

    Then later loop through the array.

    active_elements.forEach(e => document.documentElement.appendChild(e));