Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - get all table -> tr values

<table>
  <tr><td>foo</td></tr>
  <tr><td>bar</td></tr>
  <tr><td>[email protected]</td></tr>
</table>

Can anybody tell me how to write a Javascript line to only grab the email address in the table below, I've been searching a lot, but all I come across is tutorials which use "id" in either table on in td .. I want to do it without having an id .. please help

like image 322
Irfan Harun Avatar asked Dec 07 '12 12:12

Irfan Harun


2 Answers

var rows = document.getElementsByTagName("table")[0].rows;
var last = rows[rows.length - 1];
var cell = last.cells[0];
var value = cell.innerHTML

Try it yourself here: http://jsfiddle.net/ReyNx/.

Obviously you'll have to change document.getElementsByTagName("table")[0] to appropriately match your table

If you're using jQuery it's easier:

var value = $('table tr:last td').text();

For more info, see the MDN DOM reference, which shows you which properties are available on which elements to traverse the DOM.

like image 172
Matt Avatar answered Nov 04 '22 03:11

Matt


No jQuery, innerHtml or other evil / heavy functions, just plain old JavaScript:

// Get the first table in the document.
var table = document.getElementsByTagName('table')[0];
// Get the third row of this table (0-index 3rd = 2)
var emailRow = table.rows[2];
// Get this element's content.
var emailContent = emailRow.firstChild.textContent;

You could write it in 1 line:

var emailContent = document.getElementsByTagName('table')[0].rows[2].firstChild.textContent;

If you want to find all email addresses in a table:

var emails = [];
var table = document.getElementsByTagName('table')[0];
var rows = table.rows;
for (var i = 0; i < rows.length; i++) {
    var rowText = rows[i].firstChild.textContent;
    if (~rowText.indexOf('@')) { // If the content of the row contains a '@' character (This could be replaced with a regex check)
            // Also, I personally prefer to use '~' over '> -1' for indexOf(), but both would work.
        emails.push(rowText);
    }
}
console.log(emails);

Working example

like image 34
Cerbrus Avatar answered Nov 04 '22 02:11

Cerbrus