如何改变元素节点的HTML 属性

248 阅读1分钟

1,标准W3C属性,如src、href等等,只需要直接打点进行更改即可

oImg.src = 'images/2.jpg';
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 符合W3C属性 -->
    <img src="duck.png" id="pic">
    <a href="http://www.baidu.com" id="link">
    去百度</a>


    <!--  不符合W3C属性-->
    <div id="box"> </div>
    <script>
        // 符合W3C属性设置
        var oPic= document.getElementById('pic');
        oPic.src = 'archer.png';
        var oLink= document.getElementById('link');
        oLink.href = "http://www.imooc.com";
        oLink.innerHTML ='去慕课网';

        // 不符合W3C属性设置
        var box = document.getElementById('box');
        box.setAttribute('data-n',10);

        var n = box.getAttribute('data-n');
        alert(n);

    </script>
</body>
</html

通过打点调用直接对所需操作的属性进行设置

2,不符合W3C标准的属性,要使用setAttribute()和getAttribute()来设置、读取

oBox.setAttribute('data-n,10);
var n = oBox.getAttribute('data-n');
alert(n);