JS獲取元素屬性和ES6獲取自定義屬性

獲取元素的屬性分爲兩種類型:

1. 獲取和設置元素常見的屬性(class,id,type,value…)

//js
  設置屬性 .setAttribute("屬性","值")
  獲取屬性 .getAttribute("屬性")
//jQuery
  設置屬性 .attr("屬性","值")
  獲取屬性 .attr("屬性")

2. 獲取自定義的元素的屬性(data-value,data-mess…)

<!DOCTYPE html>
<html> 
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>獲取元素屬性</title>
        <style>
            * {
                margin:0;
                padding:0;
                list-style:none;
            }
        </style>
    </head>
     
    <body>
        <div id="mayouchen">
            <div style="background:red;height:20px">元素屬性獲取</div>
            <div class="test1">
                <p id="demo">點擊按鈕來設置按鈕的 type,id,class 屬性。</p>
                <input value="OK" class="mayouchen">
                <button onclick="mayouchen1()">獲取元素屬性</button>
            </div>
            <div style="background:green;height:20px">自定義屬性獲取</div>
            <div class="test2">
                <div id="tree" data-leaves="47" data-plant-height="2.4m">我是被獲取的元素</div>
                <button onclick="mayouchen2()">獲取自定義元素屬性</button>
            </div>
        </div>
        <script src="https://cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script>
        <script>
            $(function() {
 
            });
 
            function mayouchen1() {       //常見屬性的設置和獲取
                document.getElementsByTagName("INPUT")[0].setAttribute("type", "button");
                document.getElementsByTagName("INPUT")[0].setAttribute("class", "mayouchen");
                document.getElementsByTagName("INPUT")[0].setAttribute("id", "test1");
 
                document.getElementsByTagName("INPUT")[0].getAttribute("id");
                document.getElementsByTagName("INPUT")[0].getAttribute("class");
 
            }
 
            function mayouchen2() {     //自定義屬性的設置和獲取
                var tree = document.getElementById("tree");
                //getAttribute()取值屬性
                console.log("data-leaves======" + tree.getAttribute("data-leaves"));
                console.log("data-plant-height===============" + tree.getAttribute("data-plant-height"));
 
                //setAttribute()賦值屬性
                tree.setAttribute("data-come", "49");
 
                //data-前綴屬性可以在JS中通過dataset取值,更加方便
                console.log("通過dataset獲得data-leaves====" + tree.dataset.leaves);
                console.log("通過dataset獲得data-plant-height====" + tree.dataset.plantHeight);
 
                //注意在這裏連字符的訪問時,屬性要寫成駝峯形式
            }
        </script>
    </body>
 
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章