seannie
November 28, 2013, 3:14pm
1
I want to have a link to add to each of the elements in the array below:
var test = ['Test1','Test2','Test3','Test4' ];
I tried to add <a href =“#”>Test1</a> for example but to no effect.
Is there a way of doing this within the array.
Thanks for any help.
Hi there,
I’m afraid I don’t quite understand this:
I want to have a link to add to each of the elements in the array below:
You have an array containing four elements and each element is a string.
What do you want to do after that?
Do you want to add a link to the array?
Or do you want to use the elements stored in the array to create a link?
If you could elaborate a little on what you are trying to do, I’m sure we could help.
seannie
November 28, 2013, 3:51pm
3
I want to create links for each of these elements so that they are directed to specific pages.
For example within the array is it possible to have ‘<a hef=“test1.htm”>Test1</a>’ and ‘<a hef=“test2.htm”>Test2</a>’ etc. so that the link for each element is stored internally within the array.
I’m using it because I wanted the array to populate a dropdown select list and the array populates based on an original select.
Well, you could store the elements in the array as a string then append them to a target element using innerHTML:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Array of links</title>
</head>
<body>
<div id="linkTarget"></div>
<script>
var linkArray = ['<a href="test1.htm">Test1</a>', '<a href="test2.htm">Test2</a>'],
linkTarget = document.getElementById("linkTarget"),
i,
len = linkArray.length;
for (i=0; i<len; i++){
linkTarget.innerHTML += linkArray[i];
}
</script>
</body>
</html>
However, it would be cleaner to use an object literal and store the link’s href value and the link’s text as key value pairs:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Array of links</title>
</head>
<body>
<script>
var linkList = {
"test1.htm": "Test1",
"test2.htm": "Test2"
};
for (link in linkList) {
if (linkList.hasOwnProperty(link)) {
var a = document.createElement('a'),
linkText = document.createTextNode(linkList[link]);
a.href = link;
a.appendChild(linkText);
document.body.appendChild(a);
}
}
</script>
</body>
</html>