balintpekker
balintpekker

Reputation: 1844

Append array to a class in javascript

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?

Upvotes: 1

Views: 91

Answers (2)

prashant gedam
prashant gedam

Reputation: 40

$("#menu").find('li').each(function(i){
    $(this).append(menuElm[i]);
});

/* if you want to use jquery here is the code to append */

Upvotes: 0

Quentin
Quentin

Reputation: 943217

menuElm.length

The ul element doesn't have a length, so you are looping from 0 to 0, which is 0 iterations.


menuElm = createElm("ul");

This function isn't defined. You need document.createElement('ul');


menuElm = createElm("ul");
menuElm.id = ++k;

You appear to be creating one list item, and then changing its ID and appending it multiple times.

You need a new list item each time you go around the loop.


appendChild(menuElm[i]);

You've been treating menuElm as an element previously. It isn't an array, [i] makes no sense here.

Upvotes: 4

Related Questions