JS - 事件 - 节点属性的操作

节点属性的操作

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>JS</title>
    </head>
    <body>
        <div id="box">
            <button class="btn">按钮</button>
            <span id="span">
                <a href="#">百度一下</a>
            </span>
            <p>我是段落</p>
        </div>
        <script type="text/javascript">
            window.onload = function() {
             //节点的属性操作
                var img = document.getElementsByTagName("img")[0];

            //获取节点的属性getAttribute
                console.log(img.getAttribute("src"));
                console.log(img.src);

            //设置节点的属性
                img.setAttribute("src", "icon-2.jpg"); //自身带有的属性
                img.setAttribute("aaa", "bbb"); //动态添加的属性
                console.log(img.src); //自身的属性通过点语法获得
                console.log(img.getAttribute("aaa")); //不属于自身的属性通过getAttribute获得
            
            //删除节点的属性
            img.removeAttribute("src");
         }
        </script>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_37580235/article/details/80761712
今日推荐