1. 程式人生 > >js實驗-DOM操作

js實驗-DOM操作

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
    <link rel="stylesheet" href="./2.css">
</head>
<body>
<div class="wrapper">
    <div class="block" style="border-right: black 2px solid ">
        <h3>待選名單</h3>
        <div>
            <ul id="box1">
                <li>
                    <label for="li1">小紅</label>
                    <input type="checkbox" name="list1" id="li1">
                </li>
                <li>
                    <label for="li2">小黃</label>
                    <input type="checkbox" name="list1" id="li2">
                </li>
                <li>
                    <label for="li3">小藍</label>
                    <input type="checkbox" name="list1" id="li3">
                </li>
                <li>
                    <label for="li4">小綠</label>
                    <input type="checkbox" name="list1" id="li4">
                </li>
            </ul>
        </div>
    </div>
    <div class="block">
        <br>
        <button id="rm">移出</button><br>
        <button id="put">移入</button>
    </div>
    <div class="block" style="border-left: black 2px solid ">
        <h3>參選名單</h3>
        <ul id="box2">

        </ul>
    </div>
</div>

<script src="./2.js"></script>
</body>
</html>

JavaScript

function remove(){
    var l2 = document.getElementsByName("list2");
    var l1 = document.getElementById("box1");
    for(var i = l2.length-1; i >= 0; i--)    //此處必須為逆序,防止列表元素刪除後元素下標改變造成的邏輯錯誤
        if(l2[i].checked){
            var tmp = l2[i].parentNode;
            l2[i].parentNode.parentNode.removeChild(l2[i].parentNode);
            tmp.childNodes[3].name = "list1";
            tmp.childNodes[3].checked = false;
            l1.appendChild(tmp);
        }
}

function insert(){
    var l1 = document.getElementsByName("list1");
    var l2 = document.getElementById("box2");
    for(var i = l1.length-1; i >= 0; i--)
        if(l1[i].checked){
            var tmp = l1[i].parentNode;
            l1[i].parentNode.parentNode.removeChild(l1[i].parentNode);
            tmp.childNodes[3].name = "list2";
            tmp.childNodes[3].checked = false;
            l2.appendChild(tmp);
        }
}

//這裡採用事件監聽的方式,做到了JavaScript和HTML程式碼分離
var x = document.getElementById("rm");
x.addEventListener("click",remove);

var y = document.getElementById("put");
y.addEventListener("click",insert);

DOM解析HTML和解析XPath、python bs4解析HTML的思路同出一轍,此處不做贅述。

document.getElementById與getElementByName的區別