praveenjayapal
praveenjayapal

Reputation:

Fetch the data of a particular <td> in a table

I need to get the data of an particular <td>, but I don't have any id or name for that particular <td>. How do you get the contents of that <td>?

For example:

<table>
  <tr><td>name</td><td>praveen</td></tr>
  <tr><td>designation</td><td>software engineer</td></tr>
</table>

Is it possible to get the value "designation" from this table.. I need to extract the word "software engineer" using javascript.

Upvotes: 2

Views: 2466

Answers (5)

roenving
roenving

Reputation: 2636

Tomalak's a little quicker:

<script type="text/javascript">
function getText(tText){
  var tds = document.getElementsByTagName("td");
  for(var i=0, im=tds.length; im>i; i++){
    if(tds[i].firstChild.nodeValue == tText)
      return tds[i].nextSibling.firstChild.nodeValue;
  }
}
</script>

Upvotes: 0

Jeff Schumacher
Jeff Schumacher

Reputation: 3156

I prefer to use jQuery to do all the heavy lifting for this sort of task.

For example, the following function will return the text of the next element of the same type that you're searching for:

function GetNextChildText(tagToFind, valueToFind) {
    var nextText = "";
    $(tagToFind).each(function(i) {
        if ($(this).text() == valueToFind) {
            if ($(this).next() != null && $(this).next() != undefined) {
                nextText = $(this).next().text();
            }
        }
    });
    return (nextText);
}

So, for your example table, your call to return the designation could be:

var designationText = GetNextChildText('td', 'designation');

And the result is that the variable designationText would contain the value 'software engineer'.

Upvotes: 3

Tomalak
Tomalak

Reputation: 338128

A quick solution:

function GetTdContent(label)
{
  var TDs = document.getElementsByTagName("TD");
  var foundFlag = false;

  for (i = 0; i < TDs.length; i++)
  {
    if (foundFlag) return TDs[i].innerHTML;
    foundFlag = TDs[i].innerHTML.toLower() == label.toLower(); 
  }
}

elsewhere call:

var value = GetTdContent("designation");

Explanation:

The function iterates all TDs in the document. If it finds one with the given label, say "designation", it loops one more time and returns the next TD content.

This makes a few assumptions about your source HTML. If you know your data though, it can be enough.

Upvotes: 2

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

Use XPath (tutorial here, including instructions for IE and other browsers: http://www.w3schools.com/XPath/xpath_examples.asp)

The xpath for your example is

//table/tr/td[text()="designation"]/following::td

("the td that follows the td with text "designation" that's in a tr that's in a table somewhere in the document")

Simpler Xpaths are possible - if it's the only table cell that could contain 'designation' you could use

//td[text()="designation"]/following::td

One issue with writing code to do the particular search is that it needs changing, possibly significantly, if the structure of your page changes. The Xpath may not need to change at all, and if it does, it's only one line.

Upvotes: 0

VonC
VonC

Reputation: 1323183

Something along the line of:
(not tested, just quick code to give an idea)

var tables = document.getElementById('TABLE'); // instead of document.all.tag
var rows;
var cells;
var maxCells = 1;
var designation;
if (tables) {
    for (var t=0; t<tables.length; t++) {
        rows = tables[t].all.tags('TR');
        if (tables[t].all.tags('TABLE').length == 0) {
            for (var r=0; r<rows.length; r++) {
                if (rows[r].innerText != '') {
                    cells = rows[r].all.tags('TD');
                    for (var c=0; c<cells.length; c++) {
                        if (cells[c].innerText == 'designation' && c<(cells.length-1)) {
                            designation = cells[c+1].innerText;
                        }
                    }
                }
            }
        }
    }
}

Since document.all is IE specific, you should rather user getElementById, with the following to redefine that function for IE:

if (/msie/i.test (navigator.userAgent)) //only override IE
{
    document.nativeGetElementById = document.getElementById;
    document.getElementById = function(id)
    {
        var elem = document.nativeGetElementById(id);
        if(elem)
        {
            //make sure that it is a valid match on id
            if(elem.attributes['id'].value == id)
            {
                return elem;
            }
            else
            {
                //otherwise find the correct element
                for(var i=1;i<document.all[id].length;i++)
                {
                    if(document.all[id][i].attributes['id'].value == id)
                    {
                        return document.all[id][i];
                    }
                }
            }
        }
        return null;
    };
}

Upvotes: 1

Related Questions