How do I output the ID names ok1
, ok2
, ok3
inside a Javascript function?
<table>
<tr>
<td id="col1"><a id="ok1" href="javascript:void(0);">click</a></td>
<td id="col2"><a id="ok2" href="javascript:void(0);">click</a></td>
<td id="col3"><a id="ok3" href="javascript:void(0);">click</a></td>
</tr>
</table>
for example alert(something);
outputs ok1
How do I output the ID names ok1
, ok2
, ok3
inside a Javascript function?
<table>
<tr>
<td id="col1"><a id="ok1" href="javascript:void(0);">click</a></td>
<td id="col2"><a id="ok2" href="javascript:void(0);">click</a></td>
<td id="col3"><a id="ok3" href="javascript:void(0);">click</a></td>
</tr>
</table>
for example alert(something);
outputs ok1
- You should set onclick="somehting(this)" and inside the function you will have a reference to the anchor. – Alejandro Ocampo Commented Sep 14, 2015 at 17:53
- You probably shouldn't have multiple ids per element stackoverflow./questions/192048/… – camiblanch Commented Sep 14, 2015 at 17:55
- It's not clear what you mean by "getting the id of ok1" – Daniel Rosano Commented Sep 14, 2015 at 18:04
- Have you tried something? This is pretty basic stuff. – Michelangelo Commented Sep 14, 2015 at 18:05
-
@DanielRosano I want to get all the IDs (
ok1
,ok2
,ok3
) inside a javascript function – Milad Commented Sep 14, 2015 at 18:13
5 Answers
Reset to default 3If you are activating a handler directly on that element, such as onclick
you can just do this.id
, meaning get the id
attribute of the element:
document.getElementById("ok1").onclick = function(){
console.log(this.id);
}
Fiddle Example - Click the first item, at the id will be shown in the console. The same approach can be done with the other two elements.
Edit To simply get all the elements of <a>
inside a table you can do this:
var children = document.querySelectorAll("#myTable tr td a");
for(var i=0; i<children.length; i++) {
console.log(children[i].id);
}
Note I've changed the HTML, as you might not want to do this for all your tables. So I've added an id to it:
<table id="myTable"> ... </table>
Updated Fiddle
Collect all the a
tags and loop over it getting the attribute id
in the function:
(function () {
var links = document.getElementsByTagName('a');
for (var i=0; i<links.length; i++) {
console.log(links[i].getAttribute('id'));
}
})()
Since the id is used as a CSS Selector in your .css file you can get the id "ok1" by doing
#ok1 {
...
}
use onClick event
<td id="col1"><a id="ok1" href="javascript:void(0);" onclick="clickFun(this)">click</a></td>
see this link
ok see this Code it's work perfect. Hope you satisfy....
var parent_ = this_.parentNode.parentNode.querySelectorAll("a");
for(var i=0; i<parent_.length; i++)
{
alert(parent_[i].getAttribute("id"));
}
see this link