Links

An array is created of all the links in a page allowing you to use the link object to reference the document.links property array.

To find the number of links in the page you would use

document.links.length

You can then use the link array to reference a link.

Test Link 1 is the first link in this page and is referenced as

document.links[0] where 0 is the ordinal number.

Use these buttons to get the url and text of this link

This was done by using document.links[0] and document.links[0].innerHTML

You can change the url and text of this link by using
document.links[0].href='newPage.htm' and document.links[0].innerHTML='New Page'

After pressing one of the following 2 buttons press the appropriate button above and see that the relative link value has changed

Once these value are changed you will have to refresh the page to reload the default values for that link.


You can define a group of links within a page simply by nesting the links inside a div.
You would then find out how many links are in this group by referencing the group like this

document.getElementById('group1').getElementsByTagName('A')

<script type="text/javascript">
<!--
function chk_group1(){
group1_elements=document.getElementById('group1').getElementsByTagName('A')
link_href=""
link_text=""
for(var i=0;i<group1_elements.length;i++){
link_href+=group1_elements[i].href+"\n"
link_text+=group1_elements[i].innerHTML+"\n"
}
alert("There are " + group1_elements.length + " links in group 1\n\n" + link_href + "\n\nThe text for these links is\n" + link_text)
}
// -->
</script>

<div id="group1">

<a href="page1.htm">Page 1</a>
<a href="page2.htm">Page 2</a>
<a href="page3.htm">Page 3</a>
<a href="page4.htm">Page 4</a>

</div>

<input type="button" value="Check Group 1" onclick="chk_group1()">


Once you know how to reference links you can get or change values associated with a particular link.
We've already seen that the href value and text value of a link can be change but you can also change the title text, use css, add or change the links ID

document.links[n].title="HELLO WORLD"
document.links[n].style.color="red"
document.links[n].id="active_link"
document.links[n].style.fontStyle="italic"

<a href="page5.htm">Page 5</a>
<a href="page6.htm">Page 6</a>
<a href="links.htm">Links</a>
<a href="page8.htm">Page 8</a>

Note:
An alternative method to using document.links is getElementsByTagName('A')