JavaScript学习 - 基础(八) - DOM 节点 添加/删除/修改/属性值操作

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);

猜你喜欢

转载自www.cnblogs.com/Anec/p/9844972.html