JS中获取父节点元素和子节点元素

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <table>
        <tr>
            <td>1td>
            <td>2td>
            <td>3td>
        tr>
        <tr>
            <td id="t1">1td>
            <td>2td>
            <td>3td>
        tr>
        <tr>
            <td>1td>
            <td>2td>
            <td>3td>
        tr>
    table>
body>
<script>
    window.onload = function(){
        //找到td
        var t1 = document.getElementById('t1');
        //获取父节点元素
        var tr = t1.parentNode;
        tr.style.backgroundColor = 'yellow';
        //获取子元素节点
        var t2 = tr.firstElementChild;
        t2.innerText = '111';
        var t3 = tr.lastElementChild;
        t3.innerText = '333';
        //前一个元素节点
        var t4 = t3.previousElementSibling;
        t4.innerText = '改变了'
        //后一个元素节点
        /*var t5 = t4.nextElementSibling;
        t5.innerText = '12';*/
    }
script>
html>

你可能感兴趣的:(HTML5+JS)