Obtaining the index of the anchor that was clicked through the dom

T

Terry

Hi folks.

I was wondering if I have a bunch of anchors that all have the same
function which is being called when a user click on them can I obtain
the index of the anchor calling the function through the dom? I was
thinking about using document.getElementsByTagName('a') somehow.

My code would look something like this:

<a href="" onclick="showContent()">Breakfast</a>
<a href="" onclick="showContent()">Lunch</a>
<a href="" onclick="showContent()">Dinner</a>

I have a feeling it can be done using a loop within showContent but I
was hoping that it can be done without having to loop.

Thanks,
Terry
 
T

Thomas 'PointedEars' Lahn

Terry said:
I was wondering if I have a bunch of anchors that all have the same
function which is being called when a user click on them can I obtain
the index of the anchor calling the function through the dom? I was
thinking about using document.getElementsByTagName('a') somehow.

My code would look something like this:

<a href="" onclick="showContent()">Breakfast</a>
<a href="" onclick="showContent()">Lunch</a>
<a href="" onclick="showContent()">Dinner</a>

Don't do that. What about users without client-side script support?
Instead, write for example

<a href="alternative" onclick="showContent(this); return false">Dinner</a>

But think about it before you do such. Are your objects actually
hyperlinks? If not, `a' is probably the wrong element.

<script type="text/javascript">
document.write(
'<input type="button" value="foo" onclick="bar('baz')">);
I have a feeling it can be done using a loop within showContent but I
was hoping that it can be done without having to loop.

Google for "event bubbling".


PointedEars
 
T

Thomas 'PointedEars' Lahn

Thomas said:
<script type="text/javascript">
document.write(
'<input type="button" value="foo" onclick="bar('baz')">);
</script>

<script type="text/javascript">
document.write(
'<input type="button" value="foo" onclick="bar(\'baz\')">');
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top