views:

78

answers:

2
+1  Q: 

javascript tables

I'm having an issue with looping through a table in javascript and getting the text from the first cell of a row. I want to get the text of this cell so that I can compare it with something else and remove the row if the text matches. When I try to get the text though, all that actually comes out is "[object text]". Can anyone tell me how to actually get the text. My code below works for looping through all the rows of the table and I think it is getting the correct cell. Thanks!

function addRow(id, sender, message){
var theTable = document.getElementById('messageTable');
var lastRow = theTable.rows.length;
var newRow = theTable.insertRow(lastRow);
newRow.id = id;

var cellLeft = newRow.insertCell(0);
var textNode = document.createTextNode(id);
cellLeft.appendChild(textNode);

var secondCell = newRow.insertCell(1);
var textNode2 = document.createTextNode(sender);
secondCell.appendChild(textNode2);

var messageCell = newRow.insertCell(2);
var messageNode = document.createTextNode(message);
messageCell.appendChild(messageNode);

var deleteCell = newRow.insertCell(3);
var deleteNode = document.createElement('button');
deleteNode.value = 'Delete';
deleteNode.innerHTML = 'Delete';
deleteNode.onclick = function(){
 var myTable = document.getElementById('messageTable');
 var rows = myTable.childNodes;

 var i=1;
 for (i=1;i<rows.length;i++) {
  var myCell = rows[i].getElementsByTagName("td")[0];
  var myCellText = myCell.childNodes[0];
  alert(myCellText);
  if (myCellText == id){
   alert('match');
  }
  alert('done');
 }    
};
deleteCell.appendChild(deleteNode);
}
+3  A: 

This should do it:

var myCellText = myCell.childNodes[0].innerHTML;
Kevin
A: 

"this" refers to "document.createElement ( 'button');"

1st ParentNode is the cell 2nd ParentNode is the table

deleteNode.onclick = function(){
    alert(this.parentNode.parentNode.id);
};
andres descalzo
sorry, the 2nd ParentNode corresponds to the parent row
andres descalzo