12

I have a global JavaScript array that contains some strings.

I want to create a dynamic list based on the strings in my JavaScript array. Similar to this:

<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>
    <li>
        <a href='#'>String 1</a>
    </li>
</ul>

How can I iterate over my array, and then create this list in JavaScript/jQuery?

4 Answers 4

20

If you only need a flat array (i.e. not multi-dimensional and no arrays within the array), then you can do the following in plain JavaScript:

var strs = [ "String 1", "String 2", "String 3" ];
var list = document.createElement("ul");
for (var i in strs) {
  var anchor = document.createElement("a");
  anchor.href = "#";
  anchor.innerText = strs[i];

  var elem = document.createElement("li");
  elem.appendChild(anchor);
  list.appendChild(elem);
}

Then append list to whichever parent element in the body you desire.

Sign up to request clarification or add additional context in comments.

1 Comment

@Jon Newmuis How can we do this if we have arrays within an array?
5

Try this

var str = '<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>';

for(var i in $yourArray){
   str += '<li><a href="#">String 1</a></li>';
}

str += '</ul>';

$('body').append(str);

Comments

0
var $bread = $('ul.xbreadcrumbs');
$.each(yourArray, function(index, value) {
  $('<li><a href="#">' + value + '</a></li>')
    .appendTo($bread);
});

I have not tested this - just off my head. Hope this helps!

Comments

0

Yes you can. You can either user the DOM directly with createElement (see Jonathan's answer), or go an very easy route with jQuery (not tested):

var ul = "<ul>";
for(var i=0; i < arr.length; i++) {
    ul += "<li><a href=\"#\">" + arr[i] + "</a></li>";
}
ul += "</ul>";

var ulElem = $(ul);

Comments

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.