I want to make a nav that look like this:
<nav class="socialmediaicons">
<ul>
<li>
<a>
<img>
</a>
</li>
</ul>
</nav>
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<nodes.length; i++) {
myNode.appendChild(nodes[i]);
for(var j=0; j<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.