04 setAttribute()和getAttribute()用法

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        #box{
            color: red;
        }
    </style>
</head>
<body>

    <h2>你要什么</h2>
    <p title ='选择你的课程'>本课程是web课程</p>
    <ul id='classList'>
        <li class="item">javascript</li>
        <li class="item">DOM</li>
        <li>BOM</li>
    </ul>

    <script type="text/javascript">
        
        //获取属性值 getAttribute  元素节点对象获取属性值 没有属性值返回null
        var oP = document.getElementsByTagName('p')[0];
        console.log(oP);//<p title ='选择你的课程'>本课程是web课程</p>

        var title = oP.getAttribute('title');
        console.log(title);//选择你的课程

        //获取属性节点
        console.log(oP.attributes);//0: title 1: id length: 2

        //2.设置属性值,增加属性节点 第一个参数选择器  第二个选择器名字
        oP.setAttribute('id','box');//id = 'box'


    </script>

</body>
</html>
原文地址:https://www.cnblogs.com/wuhui1222/p/14171747.html