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:
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);
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!
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);
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.