0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Milad
  • 1,239
  • 3
  • 19
  • 37

5 Answers5

3

If 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

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
  • Would you mind reading the question again.. I added a few details and re-explained the issue. – Milad Sep 14 '15 at 18:26
1

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'));   
    }
})()
Michelangelo
  • 5,888
  • 5
  • 31
  • 50
0

Since the id is used as a CSS Selector in your .css file you can get the id "ok1" by doing

#ok1 {
    ...
}
0

use onClick event

<td id="col1"><a id="ok1" href="javascript:void(0);" onclick="clickFun(this)">click</a></td>

see this link

Sandeep
  • 1,461
  • 13
  • 26
0

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

Sandeep
  • 1,461
  • 13
  • 26