How to force run JS function in specific div

Viewed 178

Hi I'am trying to build table with js, but I'am not able to force it to build in specific div it always create my table outside entire section. Is there any way to force it?

HTML:

<section class="all-products" id="all-products">
    <div class="container">

        <div class="title-box">
            <h2>Products</h2>
        </div>

        <div class="row" id=products-row">

            <script>
              LoadAllProducts();
            </script>

        </div>
    </div>
</section>

load-products.js:

function LoadAllProducts() {
    var x = document.createElement("TABLE");
    x.setAttribute("id", "table");
    document.body.appendChild(x);

    var y = document.createElement("TBODY");
    y.setAttribute("id", "products");
    document.getElementById("table").appendChild(y);
}

2 Answers
 document.body.appendChild(x);

Is obviously the document.body. The program is doing exactly what you told it to do... attach the section to the main body of the document.

The program does not understand "implications", as in "I put this code here, so I expect the code to output here". JavaScript DOM does not work that way. You have to specify where the output goes.

If you want it in products-row, you have to tell it to go there

document.getElementById("products-row").appendChild(x)

In this case, we grab the element "products-rows" by its id, then tell the code "append my output x here".

The problem is that you are calling appendChild() on body.

function LoadAllProducts() {
    var x = document.createElement("TABLE");
    x.setAttribute("id", "table");
    // Instead of document.body, use document.getElementById()
    document.getElementById("products-row").appendChild(x);

    var y = document.createElement("TBODY");
    y.setAttribute("id", "products");
    // ... like you were using here...
    document.getElementById("table").appendChild(y);
}

It does not matter where the function call is located in the HTML, document.body will refer to the body element of the current page's document.

Related