Home > Web Front-end > JS Tutorial > body text

A simple example of obtaining the contents of each tr and td of the table node in js

高洛峰
Release: 2016-12-29 16:21:16
Original
1118 people have browsed it

<table id="tb1" width="200" border="1" cellpadding="4" cellspacing="0">
    <tr>
        <td height="25">第一行</td>
    </tr>
    <tr>
        <td height="25">第二行</td>
    </tr>
    <tr>
        <td height="25">第三行</td>
    </tr>
    <tr>
        <td height="25">第四行</td>
    </tr>
         <tr>
        <td height="25"><input type="button" name="getTableContent" value="获得表格内容" onclick="getTableContent(this)"></td>
    </tr>
</table>
Copy after login

As shown in the code above, the this object is passed in the button click event, and this object is the button itself. Test the data obtained from the table through the following method

<script language="javascript">
    function getTableContent(node) {
// 按钮的父节点的父节点是tr。
          var tr1 = node.parentNode.parentNode;
            alert(tr1.rowIndex);
            alert(tr1.cells[0].childNodes[0].value); //获取的方法一
alert(tr1.cells[0].innerText); 
// 通过以下方式找到table对象,在获取tr,td。然后获取td的html内容
        var table = document.getElementById("tb1");//获取第一个表格
         
        var child = table.getElementsByTagName("tr")[rowIndex - 1];//获取行的第一个单元格
                 
        var text = child.firstChild.innerHTML;
        window.alert("表格第" + rowIndex + "的内容为: " + text);
    }
</script>
Copy after login

The above is the simple example of obtaining the contents of each tr and td of the table node in js brought by the editor. I hope everyone will support the PHP Chinese website~

For more simple examples of obtaining the contents of each tr and td of table nodes in js, please pay attention to the PHP Chinese website for related articles!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template