1

I have this Javascript function which "alerts" the content of a clicked cell, wherever I click on my HTML array :

var table = document.getElementById("tableID");
if (table != null) {
   for (var i = 0; i < table.rows.length; i++) {
      for (var j = 0; j < table.rows[i].cells.length; j++)
         table.rows[i].cells[j].onclick = function () {tableText(this);};
   }
}
function tableText(tableCell) {alert(tableCell.innerHTML);}

My goal is returning only the value of the first cell of the clicked row (I've tried to manage it but I'm a newbie in Javascript...). Thanks in advance !

ALGR
  • 319
  • 1
  • 10
  • One approach would be to bind an event listener to the table like this: `table.addEventListener('click',function(e){`…`})` and in that callback function going up the DOM tree from `e.target` (i. e. `e.target.parentNode.parentNode…` until you hit a ``) and then of that `tr` returning `.children[0]`. It depends on whether you want to use a loop or jQuery or other libraries. – Sebastian Simon Jun 02 '15 at 12:39
  • use jQuery in combination with https://api.jquery.com/siblings/ and https://api.jquery.com/eq/ – rst Jun 02 '15 at 12:39

4 Answers4

2

You could also use jquery

$("#tableID tbody tr").click(function() {
    var first_td = $(this).closest("tr") // Finds the closest <tr> 
        .find("td:first") // Finds the first <td>
        .text(); // Gets its text. 
    console.log("Selected first_td is  : ", first_td);
});
cs04iz1
  • 1,737
  • 1
  • 17
  • 30
1

You can do it by getting first child from parent element. Just use tableCell.parentNode.firstChild.innerHTML instead tableCell.innerHTML

1
function tableText(tableCell) {
    alert(tableCell.parentElement.childNodes[0].innerHTML);
}

Fiddle for you to play with: https://jsfiddle.net/5z8q30jt/

Steen
  • 2,749
  • 2
  • 20
  • 36
0

If you don't want use jquery:

http://codepen.io/luarmr/pen/qdrOev

function addEvent(elem, event, fn) {
  //http://stackoverflow.com/questions/10149963/adding-event-listener-cross-browser
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}

var table = document.getElementById('test');
addEvent(table, 'click', function(e){
  var node = e.srcElement;
  while(node.tagName.toLowerCase() !== 'tr' && node.tagName.toLowerCase() !== 'body') {
    node = node.parentNode;
  }
  if(node.tagName.toLowerCase() === 'tr') {
    var td = node.getElementsByTagName('td')[0];
    alert(td.innerHTML)
  }

});
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42