Javascript - get all table -> tr values

前端 未结 8 1740
鱼传尺愫
鱼传尺愫 2020-12-28 23:02
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 23:21

    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

提交回复
热议问题
foo
bar
abc@yahoo.com