经过元素的属性node
能够直接经过元素属性获取或操做特性,可是只有公认的特性(非自定义的特性),例如id
、title
、style
、align
、className
等,注意,由于在ECMAScript中,class
是保留字(在ES6中成了关键字),因此就不能再用class
这个属性名来表示元素的CSS类名了,只能换成className
。数组
经过getAttribute()
、setAttribute()
、removeAttribute()
bash
也能够经过这三个DOM方法来操做DOM元素的特性,例如函数
let div = document.getElementById("my-div");
div.getAttribute("id"); // 获取id
div.getAttribute("title"); // 获取title
div.getAttribute("class"); // 获取元素的CSS类名,由于是传参数给getAttrbute函数,因此能够用class
div.getAttribute("dat-my-attribute"); // 获取自定义特性
div.setAttribute("id","anotherId"); // 设置id
div.removeAttribute("title"); // 删除title
复制代码
从上面能够看出来,用这种方法,不只能够获取到公认的特性,也能够获取自定义的特性。不过有两类特殊的特性,在经过属性获取和经过方法获取时获取到的却不同,一类是style
,经过属性访问获取到的是一个对象,经过getAttribute
获取到的是CSS文本;另外一类就是事件处理程序如onclick
,经过属性获取,获得的是一个函数,而经过getAttribute
获取获得的则是相应函数代码的字符串。ui
经过元素的attributes
属性spa
Element类型的DOM元素都有一个attributes
属性,如div.attributes
,这样获取到的是一个NamedNodeMap,是一个动态的集合,和数组相似,也有length
属性、能够经过下标访问遍历等,一般用途就是遍历元素特性,里面存放的是多个Att节点,每一个节点的nodeName
就是特性名称,nodeValue
就是特性的值。它有一些方法,以下:code
getNamedItem(name)
:返回nodeName
为name的节点setNamedItem(node)
:向集合中插入一个Attr节点removeNamedItem(name)
:删除集合中nodeName
为name的节点item(pos)
:返回位于数字pos位置的节点 例如要获取id,有以下代码let div = document.getElementById("my-div");
div.attributes.getNamedItem("id").nodeValue;
div.attributes["id"].nodeValue; //后两行代码均可以获取到id,下面为简写形式
复制代码
从上面能够看出,这种方式最麻烦,因此平时基本不用,通常在遍历元素的特性时才会用到。 上面三种方式中,方式1是最常使用的,其次是2,最后才是第三种方式。对象