user3034828
user3034828

Reputation: 73

how to get the id of a link onclick using javascript?

Hi may i know how can i get my id of my links using javascript? the scenario was i have 3 links i want to get the element by tagname? is it possible?

<a href="docview.php?id=25" id="1">July 3, 2013</a>
<a href="docview.php?id=26" id="2">July 10, 2013</a>
<a href="docview.php?id=27" id="3">July 17, 2013</a>

I want to display the ID of my link the one i chose and then when i click n 2nd link the id of the second link will display. tahnks

Upvotes: 0

Views: 22681

Answers (5)

Theo Anderson
Theo Anderson

Reputation: 163

Here is the code for changing the value of the label...

<!DOCTYPE html>
<html>
<body>

<a href="docview.php?id=25" id="1" onmouseover="myFunction('1')">July 3, 2013</a>
<a href="docview.php?id=26" id="2" onmouseover="myFunction('2')">July 10, 2013</a>
<a href="docview.php?id=27" id="3" onmouseover="myFunction('3')">July 17, 2013</a>

<script>
var newString = "this is the new string";
function myFunction(id) {
document.getElementById(id).innerHTML = newString;

}
</script>

</body>
</html>

the innerHTML property appends the current text to whatever you specify. Also, you would change the event from onmouseover to whatever suits your needs. Hope this helps.

Upvotes: 0

Theo Anderson
Theo Anderson

Reputation: 163

You can try the following: the function is called when the link is clicked(you can also use other events such as onmouseover) it passes the id of the element to the function and prints it to the screen. Hope this helps.

<!DOCTYPE html>
<html>
<body>

<a href="docview.php?id=25" id="1" onclick="myFunction('1')">July 3, 2013</a>
<a href="docview.php?id=26" id="2" onclick="myFunction('2')">July 10, 2013</a>
<a href="docview.php?id=27" id="3" onclick="myFunction('3')">July 17, 2013</a>

<script>

function myFunction(id) {
 var x=document.getElementById(id);
document.write(x.id);

}
</script>

</body>
</html>

Upvotes: 0

Enam
Enam

Reputation: 1268

Pure JS:

var elements = document.querySelectorAll("a");
for (var i = 0; i < elements.length; i++)
{
    elements[i].addEventListener("click", function() {
        console.log(this.id)
    }, true);
}

http://jsfiddle.net/6NXC7/1/

As far as I know querySelectorAll is faster than getElementsByTagName or either JQuery selector.

Upvotes: 2

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

  var anchor = document.getElementsByTagName('a');
  for(var i=0;i<anchor.length;i++){
     anchor[i].addEventListener("click", function() {
       alert(this.id);
        return false;
    }
  }

Upvotes: 0

suneesh
suneesh

Reputation: 304

You can use jQuery

 $("a").click(function(){
    alert(this.id);
    });

Upvotes: 2

Related Questions