Working on a userscript for this site so the only way I can add elements is to do so with JavaScript. Currently it's simple stuff, but a lot of it, and I was hoping for a way to cut down on code.
I've got this:
var elm = document.getElementById('main'),
nav = document.createElement('nav'),
ul = document.createElement('ul'),
l1 = document.createElement('li'),
l2 = document.createElement('li'),
l3 = document.createElement('li'),
l4 = document.createElement('li'),
l5 = document.createElement('li'),
l6 = document.createElement('li'),
l7 = document.createElement('li'),
nest2 = document.createElement('ul'),
nest3 = document.createElement('ul'),
nest4 = document.createElement('ul'),
nest2L1 = document.createElement('li'),
nest2L2 = document.createElement('li'),
nest2L3 = document.createElement('li'),
nest3L1 = document.createElement('li'),
nest3L2 = document.createElement('li'),
nest3L3 = document.createElement('li'),
nest3L4 = document.createElement('li'),
nest4L1 = document.createElement('li'),
nest4L2 = document.createElement('li');
nav.id = 'ps-nav';
ul.id = 'ps-ul';
l1.id = 'ps-announcements';
l1.className = 'ps-listItem';
l2.id = 'ps-sponge';
l2.className = 'ps-listItem';
nest2.id = 'ps-sponge-nest';
nest2.className = 'ps-nest';
l3.id = 'ps-plugins';
l3.className = 'ps-listItem';
nest3.id = 'ps-plugins-nest';
nest3.className = 'ps-nest';
l4.id = 'ps-generalDiscussion';
l4.className = 'ps-listItem';
nest4.id = 'ps-generalDiscussion';
nest4.clasName = 'ps-nest';
l5.id = 'ps-serverDiscussion';
l5.className = 'ps-listItem';
l6.id = 'ps-meta';
l6.className = 'ps-listItem';
l7.id = 'ps-uncategorized';
l7.className = 'ps-listItem';
elm.appendChild(nav);
nav.appendChild(ul);
ul.appendChild(l1);
ul.appendChild(l2);
l2.appendChild(nest2);
nest1.appendChild(nest2L1);
nest1.appendChild(nest2L2);
nest1.appendChild(nest2L3);
ul.appendChild(l3);
l3.appendChild(nest3);
nest2.appendChild(nest3L1);
nest2.appendChild(nest3L2);
nest2.appendChild(nest3L3);
nest2.appendChild(nest3L4);
ul.appendChild(l4);
l4.appendChild(nest4);
nest3.appendChild(nest4L1);
nest3.appendChild(nest4L2);
ul.appendChild(l5);
ul.appendChild(l6);
ul.appendChild(l7);
I've nested the indentation for higher readability.
How can I reduce the amount of code here achieving the same affect?
In plain javascript:
outerHTML
. This can be done with a multiline string.Like so:
See, also, "Why does changing the innerHTML, of my box, make my button stop working in Greasemonkey?" and similar questions.
The jQuery equivalent is: