在 JavaScript 中,使用元素的 removeAttribute() 方法可以删除指定的属性。用法如下:
removeAttribute(name)
参数 name 表示元素的属性名。
下面示例演示了如何动态设置表格的边框。
<script> window.onload = function () { //绑定页面加载完毕时的事件处理函数 var table = document.getElementByTagName("table")[0]; //获取表格外框的引用 var del = document.getElementById("del"); var reset = document.getElementById("reset"); del.onclick = function () { table.removeAttribute("border"); } reset.onclick = function () { table.setAttribute("border", "2"); } </script> <table width="100%" border="2"> <tr> <td>数据表格</td> <tr> </table> <button id="del">删除</button><button id="reset">恢复</button>
在上面示例中设计了两个按钮,并分别绑定了不同的事件处理函数。单击“删除”按钮即可调用表格的 removeAttribute() 方法清除表格边框,单击“恢复”按钮即可调用表格的 setAttribute() 方法重新设置表哥便可的粗细。
下面示例演示了如何自定义删除类函数,并调用该函数删除指定类名。
<script> function hasClass (element, className) { //类名检测函数 var reg = new RegExp ('(\\s|^)' + className + '(\\s|$)'); return reg.test (element, className); //使用正则检测是否有相同的样式 } function deleteClass (element, className) { if (hasClass (element, className)) { element.className.replace (reg, ' '); //捕获要删除样式,然后替换为空白字符串 } } </script> <div id="red" class="red blue bold">盒子</div> <script> var red = document.getElementById ("red"); deleteClass (red, 'blue'); </script>
上面代码使用正则表达式检测 className 属性值字符串中是否包含指定的类名,如果存在,则使用空字符串替换掉匹配到的子字符串,从而实现删除类名的目的。
removeAttribute
移除节点指定名称的属性。示例如下
document.getElementById('riskTypePie').removeAttribute("style");
removeAttributeNode
注:此方法不兼容IE。
使用方法:
var node=document.getElementById('chartWrap'); var attr=n.getAttributeNode('style'); node.removeAttributeNode(attr);
异同分析
相同点
不同点
到此这篇关于JS removeAttribute()方法实现删除元素的某个属性的文章就介绍到这了,更多相关JS removeAttribute()删除元素属性内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。