了解attribute
都是操作当前元素节点中某个属性的
1.setAttribute()
作用:设置指定元素上的某个属性值。如果属性已经存在,则更新该值;否则,使用指定的名称和值添加一个新的属性。
参数:name:表示属性名称的字符串; value: 属性的值/新值。
例子:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); oDiv.setAttribute("class","box2") } </script> </head> <body> <div id="div1" title="hello" class="box" xxx="yyy">qwewe</div> </body> </html>
运行结果:
2.getAttribute()
作用:回元素上一个指定的属性值。如果指定的属性不存在,则返回 null 或 “” (空字符串)。
例子:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); alert(oDiv.getAttribute("class")); } </script> </head> <body> <div id="div1" title="hello" class="box" xxx="yyy">qwewe</div> </body> </html>
运行结果:
3.removeAttribute()
作用: 从指定的元素中删除一个属性
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); oDiv.removeAttribute("title") } </script> </head> <body> <div id="div1" title="hello" class="box" xxx="yyy">qwewe</div> </body> </html>
运行结果:
复制代码
1
2
3
4补充: 1.class的访问(点操作是通过className,而set/getAttribute是通过class) 2.自定义属性(set/getAttribute支持用户自定义属性)
最后
以上就是激情网络最近收集整理的关于了解attribute的全部内容,更多相关了解attribute内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复