views:

53

answers:

3

I am trying to set up links in an array so I have:

<a href="#" onClick="javascript: doFunction();" name="mylinks">link1</a>
<a href="#" onClick="javascript: doFunction();" name="mylinks">link2</a>
<a href="#" onClick="javascript: doFunction();" name="mylinks">link3</a>
...

And I want javascript to access the array like this:

function doAll()
{
    var i, l = document.mylinks.length;
    for (i = 0; i < l; i++)
        document.mylinks[i].on_click();
}

However when I execute doAll(), it tells me that document.mylinks.length is null or not an object. What would be the correct way to do this?

+1  A: 

You should use document.getElementsByName.

function doAll(){
    var l = document.getElementsByName('mylinks');
    for (var i in l)
        l[i].onclick();
}
Li0liQ
+1  A: 

firstly, use the dom to retrieve your anchor elements

<div id="linkContainer">
    <a href="#" onClick="alert('onclick 1');" name="mylinks1">link 1</a>
    <a href="#" onClick="alert('onclick 2');" name="mylinks2">link 2</a>
    ...
</div>

and to emmulate an onclick you should create a dummy event and dispatch it (if supported)

function doClick(link)
{
    if (document.createEvent)
    {
     var evt = document.createEvent("MouseEvents");
     evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
     link.dispatchEvent(evt);
    }
    else if (link.click)
        link.click();
}

then put it together:

var links = document.getElementById("linkContainer").childNodes;
for(var l = 0; l < links.length; l++)
{
    if(links[l].tagName && links[l].tagName.toLowerCase() == "a")
    {
     alert(links[l].name);
     doClick(links[l]);
    }
}

which works, i've tested it.

pstanton
Why create a dummy event instead of just calling onclick?
because it's more widely supported
pstanton
...or so i was told..
pstanton
A: 

with jquery:

<a class="mylinks">link1</a>
<a class="mylinks">link2</a>
<a class="mylinks">link3</a>

$(document).ready(function ()
{
    $('a.mylinks').click(doFunction);
    var doAll = function ()
    {
        $('a.mylinks').click();
    }
});
just somebody