0

I try to create a dynamic menu using jquery:

  function createMenu(array) {
            var main = $("#mainUl");
            for (var i = 0; i < array.length; i++) {          
                main.append("<li>");
                $('li').append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>");
                main.append("</li>");
            }    
        }

The menu is created, but in each li i get more than one span, there is an "inside" loop (I think...) createing more spans than needed... how can i solve/control it so each li gets one span according to the for - loop index ?

3 Answers 3

1

You are seeing that behaviour because you are appending that anchor with span in selecting all the li elements.

Try,

function createMenu(array) {
    var main = $("#mainUl");
    for (var i = 0; i < array.length; i++) {          
      var xLi =("<li>").appendTo(main);
      xLi.append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>");
      main.append(xLi);
    }    
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can do it simply as below

  function createMenu(array) {
                var main = $("#mainUl");
                for (var i = 0; i < array.length; i++) {          
                    main.append($("<li>").append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>"));
                }    
            }

Comments

0

$('li') this selector will get every li on the html so every time you iterate to create a new li element you gonna add a new span to all of them.

Try like this:

function createMenu(array) {
        var main = $("#mainUl");
        for (var i = 0; i < array.length; i++) { 
            var menuLine = $('<li>');
            menuLine.html("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + " </span></a>" );                                
            main.append(menuLine);
        }    
    }

1 Comment

can you please remove that quote from the variable menuline ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.