removeAttribute getAttribute setAttribute
2024-09-07 09:02:05
1.removeAttribute() 方法删除指定的属性。
注:removeAttributeNode() 方法从元素中删除指定的属性节点。
简单的来讲,removeAttribute() 移除元素内的属性;
<style>
.aaa{
color:red;
}
</style>
</head>
<body>
<h1 class="aaa">Hello World</h1>
<button onclick="myFunction()">点击</button>
<script>
function myFunction()
{
document.getElementsByTagName("h1")[0].removeAttribute("class"); //当点击的时候,h1的红色会变成黑色(默认黑色)应为移除了class这个属性
}
</script>
</body>
2.getAttribute() 方法通过名称获取属性的值。(属性不存在时返回null)
注:getAttributeNode() 方法从当前元素中通过名称获取属性节点。
<style>
.aaa{
color:red;
}
</style>
</head>
<body>
<h1 class="aaa">Hello World</h1>
<button onclick="myFunction()">点击</button>
<script>
function myFunction()
{
var h1=document.getElementsByTagName("h1")[0];
alert(h1.className); //两者都能有效果 aaa
alert(h1.getAttribute("class")); // aaa
}
</script>
</body>
获取 dom 节点数据请不要用其他方法,统一用getattribute,获取对象属性方括号是兼容性最广的,点号方便,但是低版本 ie 有兼容性问题。良好的编程习惯是减少bug的保证
3.setAttribute() 方法添加指定的属性,并为其赋指定的值。
*注意:如果这个指定的属性已存在,则仅设置/更改值。
和getAttribute一样,setAttribute只是用于元素节点
*
<body>
<input value="OK">
<p>点击按钮来设置按钮的 type 属性。</p>
<button onclick="myFunction()">点击</button>
<script>
function myFunction()
{
document.getElementsByTagName("input")[0].setAttribute("type","button");
}
</script>
</body>
Internet Explorer 8 以及更早的版本不支持此方法。
通过setAttribute对文档做出修改后,在通过浏览器的源代码查看时看到的仍然是改变前的属性值。这种“表里不一”的现象源自DOM的工作模式:先加载文档的静态内容,在动态刷新,动态刷新不影响文档的静态内容。
-DOM编程艺术
最新文章
- IT行业常谈的优雅
- Weblogic的安装与配置
- javaWeb之maven多数据库环境的配置信息
- Babelfish(二分查找,字符串的处理略有难度,用sscanf输入)
- Kali Linux Web 渗透测试视频教程— 第八课 nessus
- ORCALE用户授权与创建同义词
- new对象数组时的内存布局
- Puppeteer 应用容器化
- Yapi部署说明
- JavaScript 运动(缓冲运动,多物体运动 ,多物体多值运动+回调机制)
- 发现一个强大的可视化第三方库pyecharts
- Oval框架如何校验枚举类型的一种思路
- How The Kernel Manages Your Memory.内核是如何管理内存的
- 【原】Redis windows下的环境搭建
- The Win32 Rundll and Rundll32 Interface Related Topics
- Implicit declaration of function &#39;BMKCoordinateForMapPoint&#39; is invalid in C99
- Css中路径data用法
- python中文档IO的读写
- [CLPR]BP神经网络的C++实现
- mysql-5.7.17的最新安装教程
热门文章
- 吴裕雄--天生自然python学习笔记:python 用 Open CV抓取摄像头视频图像
- android 9.0 http无法访问问题
- linux下常用命令查看端口占用
- Windows电脑忘记密码
- Office 365管理中心门户
- 吴裕雄--天生自然python学习笔记:python文档操作自动生成菜单 Word 文件
- [LC] 71. Simplify Path
- scarce|component|
- 跨越真实和虚拟世界的边界——走近SIGGRAPH 2014大会
- hadoop报错:could only be replicated to 0 nodes, instead of 1