I have an array in javascript called menuElm that has <ul> elements in it:
<ul id="1"></ul>
<ul id="2"></ul>
<ul id="3"></ul>
I have a page in HTML that has the following:
<ul id="menu">
<li class="menu-item"></li>
<li class="menu-item"></li>
<li class="menu-item"></li>
</ul>
I want to add the elements of menuElm to the HTML page so it would look like this:
<ul id="menu">
<li class="menu-item">
<ul id="1"></ul>
</li>
<li class="menu-item">
<ul id="2"></ul>
</li>
<li class="menu-item">
<ul id="3"></ul>
</li>
</ul>
I have tried the following, but the <ul> elements just wont show up in the page nor in the code:
function CreateMenu() {
var menuElm;
var k = 0;
menuElm = createElm("ul");
menuElm.id = ++k;
for (var i = 0; i < menuElm.length; ++i) {
document.getElementsByClassName("menu-item")[i].appendChild(menuElm[i]);
}
}
I am new with JavaScript, what am I doing wrong?
var k = 0in the function somenuEl.idwill always be 1. Also it's unclear whatcreateElm("ul")is returning, assuming it's a shortcut fordocument.createElement(). But either way whenCreateMenurun the loop is pretty useless asmenuElmwill always be a single element so not right to usemenuElm.lengthin that case. You're better off saving the result ofdocument.getElementsByClassName("menu-item")and loop over the length of that.menuElm.lengthto3, and added thecreateElm("ul")into the loop, which is doing the same asdocument.creatElement("ul")Now it is creating the 3 ul-s with different id-s as it should be, although it doesnt add it into the classes