dom的element类型

1)getElementById

后面的nodeName和tagName都一样

            var a=document.getElementById("my_div");
            console.log(a.nodeName,a.tagName);

元素中的class还js中会变成className

元素中的属性会在js代码中被修改

            var a=document.getElementById("my_div");
            a.className="fuck";
            console.log(a);

本来可以通过对象。属性来访问数据的

后来又知道了另外的一种方法

变量.getAttribute()

变量.setAttribute()

变量.removeAttribute()

            var a=document.getElementById("my_div");
            console.log(a.getAttribute("class"),a.getAttribute("id"));

上面的getAttribute在获取class又用回他自己的原来的class 而不是className

如果要读取自定义的属性,只能getAttribute(自定义的属性通常在前面加data-)

        <div id="my_div" class="ff" data-data="me"></div>
        <script type="text/javascript">
            var a=document.getElementById("my_div");
            console.log(a.getAttribute("data-data"));

getAttribute有两种不能返回1style2onclick等事件

还有在getAttribute中后来在js代码上加上去的也不可以

            a.color="red";
            console.log(a.color);//ok
            console.log(a.getAttribute(a.color));

除非用他的朋友setAttribute


element的attribute属性

和上面的有点什么。。。get,remove,set  后面改了NamedItem

            var b=document.getElementById("my_div");
//            var a=b.attributes.getNamedItem("id").nodeValue;
            var a=b.attributes["id"];
            console.log(a);

那个getNamedItem可以用方括号[]代替,而且可以通过a.attributes["id"].nodeValue="ddddd"直接来修改

attributes属性其他方法

removeNamedItem()

setNamedItem()

上面的attribute属性一般不用,用上面的attribute方法



原文地址:https://www.cnblogs.com/vhyc/p/5863205.html