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
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
Share Improve this question asked Nov 27, 2013 at 4:25 user3034828user3034828 732 gold badges2 silver badges7 bronze badges 2- show me your javascript function – Cris Commented Nov 27, 2013 at 4:32
- Was anything helpful? – Enam Commented Nov 27, 2013 at 5:25
5 Answers
Reset to default 2You can use jQuery
$("a").click(function(){
alert(this.id);
});
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/6NXC7/1/
As far as I know querySelectorAll
is faster than getElementsByTagName
or either JQuery selector.
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>
var anchor = document.getElementsByTagName('a');
for(var i=0;i<anchor.length;i++){
anchor[i].addEventListener("click", function() {
alert(this.id);
return false;
}
}
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.