Sheehan Alam
Sheehan Alam

Reputation: 60879

How can I dynamically create an unordered list in JavaScript?

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?

Upvotes: 12

Views: 44422

Answers (4)

Vikas Naranje
Vikas Naranje

Reputation: 2402

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);

Upvotes: 5

Jon Newmuis
Jon Newmuis

Reputation: 26502

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.

Upvotes: 20

John Keyes
John Keyes

Reputation: 5604

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);

Upvotes: 0

jimbo
jimbo

Reputation: 11042

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!

Upvotes: 0

Related Questions