I have a list of a href's and I would like to create a drop down list from it.
How can i accomplish this without using jQuery?
I'm new to javascript...
I have a list of a href's and I would like to create a drop down list from it.
How can i accomplish this without using jQuery?
I'm new to javascript...
var select = document.createElement("select");
for (var i=0; i<hrefs.length; i++) {
var link = hrefs[i];
var option = document.createElement("option");
option.value = hrefs[i];
option.innerHTML = i + ": " + hrefs[i]; // this is the label
select.appendChild(option);
}
document.body.appendChild(select);
I'm not sure if the label is right; it depends on what you mean by a list of hrefs and what you want to do with the label. I'm assuming you have an array of links like ["http://google.com", ...].
If you have JavaScript 1.6 you can do something like this:
var hrefs = ['http://stackoverflow.com', 'http://example.com'],
select = document.createElement("select"),
str = hrefs.map(function(l){
return '<option>'+l+'</option>'
});
select.innerHTML = str.join('');
document.body.appendChild(select);
You can mimic .map with
if (!Array.prototype.map)
{
Array.prototype.map = function(fun /*, thisp*/)
{
var len = this.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
(via MDC - https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/map)