DOM节点的增删改查与属性设置

本文详细介绍了如何使用JavaScript进行DOM元素的创建、添加、删除及替换,并通过实例演示了如何响应按钮点击事件来实现这些操作。同时,文章还涉及了元素样式的修改,如颜色、字体大小等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

document.createElement("p") 创建一个新对象

appendchild(ele)添加,调用者是父节点

removechild(ele)删除,调用者是父节点

innerText添加文本,innerHTML添加内容

opacity:0.7 透明度

position:fixed  脱离文档流

使用position,要有top,left,right,bottom才有margin属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .div1,.div2,.div3,.div4{
            width: 300px;
            height: 100px;
        }
        .div1{
            background-color: green;
        }
         .div2{
            background-color: yellow;
        }
         .div3{
            background-color: rebeccapurple;
        }
         .div4{
            background-color: deeppink;
        }
    </style>
</head>
<body>

<div class="div1">
    <button onclick="add()">add</button>
    hello div1
</div>
<div class="div2">
    <button onclick="del()">del</button>
    hello div2
</div>
<div class="div3">
    <button onclick="change()">change</button>
    <p>hello div3</p>
</div>
<div class="div4">hello div4</div>


<script>
    function change() {
        var img=document.createElement("img");//<img src="">
        //img.setAttribute("src","meinv.jpg");
        img.src="meinv.jpg";

        var ele=document.getElementsByTagName("p")[0];
        var father=document.getElementsByClassName("div3")[0];

        father.replaceChild(img,ele)


    }
    function add() {
        var ele=document.createElement("p");//<p></p>
        ele.innerHTML="<h1>hello p</h1>";
        //ele.innerText="<h1>hello p</h1>";
        ele.style.color="red";
        ele.style.fontSize="10px";
        var father=document.getElementsByClassName("div1")[0];
        father.appendChild(ele)

    }

    function del() {
        var father=document.getElementsByClassName("div1")[0];
        var son=father.getElementsByTagName("p")[0];
        father.removeChild(son)

    }


</script>
</body>
</html>
View Code

 

转载于:https://www.cnblogs.com/jintian/p/11108975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值