JS元素属性操作方法,包括获取属性,修改属性,删除属性

226 阅读1分钟

JS元素属性操作方法,包括获取属性,修改属性,删除属性

本篇记录JS元素属性的操作的方法。其中包含获取属性两个方法,修改属性两个方法,删除属性一个方法

获取属性

element.属性

该方法通常获取自带属性,例如src href id title alt 等属性

<body>
    <div id="demo" ></div>
    <script>
        var div = document.querySelector('div');
        // 获取元素的属性值
        // element.属性
        console.log(div.id);
    </script>
</body>

element.getAttribute('属性')

该方法通常获取自定义属性。

<body>
    <div id="demo" index="1" ></div>
    <script>
        var div = document.querySelector('div');
        // 获取元素的属性值
        // element.getAttribute('属性')  get得到获取 attribute 属性的意思 我们程序员自己添加的属性我们称为自定义属性 index
        console.log(div.getAttribute('index'));
    </script>
</body>

修改属性

element.属性='值'

该方法通常用来修改自带属性,例如src href id title alt 等属性。一般采用element.属性进行修改 以src为例来记录元素属性修改的方法。

具体代码如下所示

<body>
    <button id="Revin1">Revin1</button>
    <button id="Revin2">Revin2</button> <br>
    <img src="images/Revin1.jpg" alt="" title="Revin1">

    <script>
        // 修改元素属性  src
        // 1. 获取元素
        var Revin1 = document.getElementById('Revin1');
        var Revin2 = document.getElementById('Revin2');
        var img = document.querySelector('img');
        // 2. 注册事件  处理程序
        Revin2.onclick = function() {
            img.src = 'images/Revin2.jpg';
            img.title = 'Revin2';
        }
        Revin1.onclick = function() {
            img.src = 'images/Revin1.jpg';
            img.title = 'Revin1';
        }
    </script>
</body>

element.setAttribute('属性', '值')

该方法通常针对自定义属性的修改,例如下面例子中的index就是自定义的属性,可以通过该方法进行属性修改 具体实现如下

<body>
    <button id="Revin1" index="1">Revin1</button>
    <button id="Revin2" index="2">Revin2</button> <br>

    <script>
        // 1. 获取元素
        var Revin1 = document.getElementById('Revin1');
        var Revin2 = document.getElementById('Revin2');

        // 2. 注册事件  处理程序
        Revin2.onclick = function() {
            Revin1.setAttribute('index', 3);
            console.log(Revin1.getAttribute('index'));

        }
        Revin1.onclick = function() {
            Revin2.setAttribute('index', 4);
            console.log(Revin2.getAttribute('index'));
        }
    </script>
</body>

运行结果如下

在这里插入图片描述

删除属性

removeAttribute(属性)

删除元素的属性,自带属性与自定义属性均可删除

<body>
    <div id="demo" index="1" class="nav"></div>
    <script>
        var div = document.querySelector('div');
		console.log(div.id);
        console.log(div.index);
        console.log(div);
        //  移除属性 removeAttribute(属性)    
        div.removeAttribute('index');
        div.removeAttribute('id');
        console.log(div.id);
        console.log(div.index);
        console.log(div);
    </script>
</body>

运行结果如下

在这里插入图片描述