1. 程式人生 > >JavaScript學習 - 基礎(八) - DOM 節點 添加/刪除/修改/屬性值操作

JavaScript學習 - 基礎(八) - DOM 節點 添加/刪除/修改/屬性值操作

nts pla 屬性 ssm style attribute The width ace

html代碼:

<!--添加/刪除/修改 -->
<div id="a1">
    <button id="a2" onclick="add()">add</button>
</div>

<div id="a3">
    <button onclick="del()">del</button>
</div>

<div id="a4" style="margin-top: 20px">
    <span style="width: 20px;height: 20px">hello world !!!</
span> <button onclick="change()">change</button> </div> <!--classname屬性操作--> <div id="cn" class="a11 b11 c11"> </div>

新增標簽(document.createElement(標簽))

 // 方式一(butter控件中添加事件)
    function add() {
        var a = document.createElement("span");
        a.innerText
=‘this span label!‘; var father = document.getElementById(‘a1‘) father.appendChild(a) } // 方式二(直接document獲取標簽) // // 通過的標簽,定義事件(只執行一次函數) // var s1 = document.getElementById(‘a2‘); // var father = s1.parentNode; // // var a = document.createElement("span"); // a.innerText=‘this span label!‘;
// // s1.onclick = function f() { // father.appendChild(a); // };

刪除標簽

//刪除標簽
        function del() {
            var father = document.getElementById(‘a1‘);
            var son = father.getElementsByTagName(‘span‘)[0];
            father.removeChild(son)
        }

修改/替換 標簽(replaceChild(新標簽,舊標簽))

//修改/替換 標簽
    function change() {
        //找到父標簽
        var father = document.getElementById(‘a4‘);
        //找到需要替換的舊標簽
        var son = father.getElementsByTagName(‘span‘)[0];

        //創建一個標簽
        var ne = document.createElement(‘div‘);

        // 方式一,定義創建標簽樣式
        // ne.innerHTML = ‘<div style="background-color: blue;width: 200px;height: 200px">!!!!! </div>‘;

        // 方式二,定義創建標簽樣式
        // ne.style.backgroundColor = ‘red‘;
        // ne.style.width = ‘200px‘;
        // ne.style.height = ‘200px‘;
        // ne.innerText = "this is new div !!!! "

        //方式三,通過setattribute 設置標簽樣式.
            ne.setAttribute(‘style‘,"background-color:red;width: 200px;height: 200px");

            //這種方式也可以獲取到對象的屬性值
            var ne2 = ne.getAttribute(‘style‘);
            console.log(ne2)
            //輸出為:background-color:red;width: 200px;height: 200px

        //通過父標簽 替換新舊標簽
        father.replaceChild(ne,son)
    }

classname 屬性操作

//classname屬性操作
        var classmame = document.getElementById(‘cn‘)

        //返回classname
        console.log(classmame.className);
        //class列表
        console.log(classmame.classList);
        console.log(classmame.classList[0]);
        console.log(classmame.classList[1]);
        console.log(classmame.classList[2]);

        //增加classname
        classmame.classList.add("d11");
        console.log(classmame.className);
        //移除classname
        classmame.classList.remove("d11");
        console.log(classmame.className);

JavaScript學習 - 基礎(八) - DOM 節點 添加/刪除/修改/屬性值操作