Norbetto89 Norbetto89 - 1 month ago 9
HTML Question

JS - document.createElement does not work

I have the following code:

function icon(link) {
var iccon = document.createElement('div');
var iccons = document.createElement('td');
iccon.setAttribute('id', 'icon');
icons.appendChild(iccons);
iccon.setAttribute('onclick', 'window.open("' + link + '");');
iccons.appendChild(iccon);
var icons = document.getElementById('icons');
};


The HTML code is here.

Answer

Even though it's hard to say what you're trying to achieve with the code, I must say that it's an ordering error: you want to append the newly created items to the #icons element, which you declare at the very end.
Move the last statement to the top of the function and everything will work as expected:

function icon(link) {
    var icons = document.getElementById('icons');
    var iccon = document.createElement('div');
    var iccons = document.createElement('td');

    iccon.setAttribute('id', 'icon');
    icons.appendChild(iccons);
    iccon.setAttribute('onclick', 'window.open("' + link + '");');
    iccons.appendChild(iccon);
};

Here's the updated demo: http://codepen.io/gion/pen/NRmgPJ

I must say that you should be more careful about naming. Things get hard to read when they aren't named well.

Comments