Weird Thoughts From Eric's Head

Tags - Categories : All | AJAX | BUSINESS | PERSONAL | PROGRAMMING | BOOK REVIEW

Birthday Gift
Adam was talking to his friend at the bar, and he said, "I don't know what to get my wife for her birthday - she has everything, and besides, she can afford to buy anything she wants, so I'm stuck." His friend said, "I have an idea! Why don't you make up a certificate saying she can have 60 minutes of great sex, any way she wants it. She'll probably be thrilled." Adam decided to to his friend's advice.

The next day at the bar his friend said, "Well? Did you take my suggestion?"

"Yes, I did," Adam replied.

"Did she like it?"

"Oh yes! she jumped up , thanked me, kissed me on the forehead and ran out the door, yelling "I'll be back in an hour!!"

Grab the contents of a table cell
Well today is my 25th birthday, hence the joke above. I still feel like a nerd and I know I am going to get nerdy gifts from my fiancee. Well back to the JavaScript part of this blog.

Well The following is in response to a question that was posted on JavaRanch. I thought that this could be useful to other people so here it is.

It is not that hard to grab the text of a table cell as long as you have an id, object reference, or know the position of the cell. You will need to use innerHTML which allows you to grab the text in the cell.

If the cell you want is named it is rather easy all you need to do is reference the id

var theText = document.getElementById("cellID").innerHTML;
But if you do not have an id to go by, it takes a couple more steps, but it is not that hard as long as you know the number of the row it is in and the number of the cell it is in:
//get the table element object
var theTable = document.getElementById("tableID");
//Grab all of the rows for the table (makes an array)
var theRows = theTable.getElementsByTagName("tr");
//Grab the cells for the 2nd row (remember 0 is first)
var theCells = theRows[1].getElementsByTagName("td"); //Header would be th
//now you have the rows an array
//Grab the 3rd cells text
var theText = theCells[2].innerHTML
If you have the row named, or you have the row object, you can just do:
var theRow = document.getElementById("rowID");
var theCells = theRow.getElementsByTagName("td");
var theText = theCells[2].innerHTML
Hope that helps you out.

Eric Pascarello
Moderator of HTML/JavaScript at www.JavaRanch.com
Author of: JavaScript: Your Visual Blueprint for Dynamic Web Pages