2023-07-18T14:13:32.png
2023-07-18T14:13:44.png

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="box" age="18" sex="male">文本</div>
    <script>
        //获取元素
        var box = document.getElementById("box");
        //输出元素的id(自有属性)
        console.log(box.id);
        //输出元素的age属性值(自定义属性)
        console.log(box.getAttribute("age"));
        //输出元素的sex属性值
        console.log(box.getAttribute("sex"));
        //也可调用自有属性值(id等)
        console.log(box.getAttribute("id"));


        //设置属性的值
        //将age由18改为52
        box.setAttribute("age","52");
        //将id由box改为ddd
        box.setAttribute("id","ddd");

        //添加新的属性和值
        box.setAttribute("city","uuuu");
        //添加class并设置值
        box.setAttribute("class","sss");

        //移除属性
        box.removeAttribute("age");
        box.removeAttribute("class");



    </script>
</body>
</html>