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>

你可能感兴趣的:(h5,webApp,Javascript)