Search code examples
javascriptappendchildcreateelement

Is there a way of creating an element and sending it to another function that "appendChild"?


I have made a variable that is a function. This function is creating an Element, applies style and returns the variable within the function.

I later have a for-loop that has a "if" that wants to add that element to an already existing div by using "appendChild", but I do not manage to make it work.

Any suggestions?

var wall = function () {

    var tmp_wall = document.createElement('div');

    document.getElementById("g_world").appendChild(tmp_wall);
}

var ground = function () {

    var tmp_ground = document.createElement('div');

    document.getElementById("g_world").appendChild(tmp_ground);
}

// *****************************************************************

var world = [
    [1,1],
    [2,2],
];

function drawWorld () {

    for(var y = 0; y < world.length; y++) {

        for(var x = 0; x < world[y]; x++) {

            if(world[y][x] === 1) {
                wall();
            }
            else if (world[y][x] === 2) {
                ground();
            }
        }
        document.getElementById('g_world').innerHTML += '<br>';
    }
}

Solution

  • This looks a bit strange:

    document.getElementById('g_world') += document.body.appendChild(ground);
    

    appendChild works like this:

    document.getElementById('g_world').appendChild(ground());
    

    Can you try and check if that works?

    Also, your script won't continue after the return statement. Maybe there are some semicolons missing in your example code?

    EDIT: Your problem is in the second for-loop. You forgot to add .length, like this:

    for(var x = 0; x < world[y].length; x++) {