Nesting elements with appendChild I want to make a nav that look like this:

&lt;nav class="socialmediaicons"&gt;
   &lt;ul&gt;
     &lt;li&gt;
       &lt;a&gt;
        &lt;img&gt;
      &lt;/a&gt;
    &lt;/li&gt;
  &lt;/ul&gt;
&lt;/nav&gt;


Using the appendChild() method, and this is what I've done:

The myNode is the nav tag which has already been created via HTML.

var myNode = document.querySelector('.socialmediaicons');

var myEl = document.createElement('ul');

var myLi = document.createElement('li');

var myA = document.createElement('a');

var myImg = document.createElement('img');



var addEl = function() {
    var nodes = [myEl, myLi, myA, myImg];

    for(var i=0; i&lt;nodes.length; i++) {
        myNode.appendChild(nodes[i]);

        for(var j=0; j&lt;3; j++){
            nodes[j].appendChild(nodes[j+1]);
        }
    }

};

addEl();
console.log(myNode);


And it WORKS!!

I even added a src attribute to the myImg element using myImg.src= and the photo shows up. But is this code GOOD!?

Is there any better way to do it? (If you have a jQuery method it's OK, but show me the pure JavaScript method after it.) I like the pure JavaScript way and also for learning purposes.
A better way is by using a template library like Handlebars.

The reason why it is better, stand on the fact you could separate logic code from your visualization code.

And more, using templates, you could have a closer look on what the page will became by looking to html code with the placeholders, that is easy to debug, instead of following complicated sequences of DOM calls.

I kindly suggest you to use such type of approach.

UPDATE

In response of your comment I'm extending my answer.

About your code, the issue I see is that you define an array of DOM element inside your function, but those elements are defined outside the scoop of your function.

This is like a nightmare to maintenance, and could easily be avoided.

Just pass the DOM object as the function arguments, and you have solved the issue:

var addEl = function(rootNode) {
    var nodes = Array.prototype.slice.call(arguments, 1);

    for(var i=0; i&lt;nodes.length; i++) {
        rootNode.appendChild(nodes[i]);

        for(var j=0; j&lt;3; j++){
            nodes[j].appendChild(nodes[j+1]);
        }
    }
};