user1865365
user1865365

Reputation: 21

Get id of a span in JavaScript.

I want to get the span id in JavaScript following code always returning M26 but I want different values on different click M26 or M27:

function clickHandler() {
    var xid= document.getElementsByTagName("span");
    var xsp= xid[0].id;   
    alert(xsp);     
} 
}

<html>
    <BODY LANGUAGE = "javascript" onClick = "clickHandler();">
        <a href="javascript:void(0)"><u><b><span id=M26>2011-  
        2012</span></b></u></a>   
        <div id=c26 STYLE="display:none">
            <a href="javascript:void(0)"><u><b><span id=M27>2012-  
            2013</span></b></u></a>   
        <div id=c27 STYLE="display:none"> 
    </body>
</html>

Upvotes: 0

Views: 14036

Answers (3)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76408

There are several ways to get the id of the element that has just been clicked:

Pass a reference to this to the handler:

onclick="handlerFunc(this);">

Or, better yet, pass the event object to the handler, this allows you to manipulate the event's behaviour, too:

onclick='handlerFunc(event);'>
//in JS:
function handlerFunc(e)
{
    e = e || window.event;
    var element = e.target || e.srcElement;
    element.id;//<-- the target/source of the event (ie the element that was clicked)
    if (e.preventDefault)
    {//a couple of methods to manipulate the event
        e.preventDefault();
        e.stopPropagation();
    }
    e.returnValue = false;
    e.cancelBubble = true;
}

Upvotes: 0

Dineshkani
Dineshkani

Reputation: 3015

You can use getAttribute() function for this...

function clickHandler() {
var xid= document.getElementsByTagName("span");
var xsp= xid[0].getAttribute('id');   
alert(xsp);     
} 


<html>
<body LANGUAGE = "javascript" onload = "clickHandler();">
    <a href="javascript:void(0)"><u><b><span id=M26>2011-  
    2012</span></b></u></a>   
    <div id=c26 STYLE="display:none">
        <a href="javascript:void(0)"><u><b><span id=M27>2012-  
        2013</span></b></u></a>   
    <div id=c27 STYLE="display:none"> 
</body>
</html>

See working Demo

Upvotes: -1

Jon Taylor
Jon Taylor

Reputation: 7905

The problem you are facing is that var xid= document.getElementsByTagName("span"); gets all spans on the page regardless of where you click.

To solve this problem you should just pass a reference to the clicked object within the function. For example:

<span id=M26 onclick="clickHandler(this);" >2011-2012</span>

Then in your javascript code:

function clickHandler(object) {
    alert(object.id);
}

However it is a good idea to bind the events within javascript rather than inline in the html tags.

This article describes the different ways in which you can bind events to elements.

Upvotes: 3

Related Questions