Search code examples
javascriptwrapperappendchildcreateelement

Add div wrapper using pure JavaScript


I am trying to create a Twitters Bootstrap grid function using pure Javascript.

The problem is that the column is placed outside the row, but it should be inside. Just like

<div class="row">
    <div class="col-md-12"></div>
</div>

Right now my code posted below has this output

<div class="row"></div>
<div class="col-md-12"></div>

I tried to set the first inserted div as parent, but somehow when I use the parentNode property it returns always null.

Maybe someone can point me in the right direction?

This is my code so far

    var docFrag = document.createDocumentFragment();

    // Add row
    var row = document.createElement('div');
        row.className = 'row';
    docFrag.appendChild(row);

    // Add column
    var col = document.createElement('div');
        col.className = 'col-md-12';
    docFrag.appendChild(col);

    document.body.appendChild(docFrag);

Solution

  • You're appending it to the document fragment, not the row in the document fragment.

    Change

    docFrag.appendChild(col);
    

    To

    row.appendChild(col);
    

    If you want it to be inside the row.