JavaScript removeAttribute() 方法详解:删除元素属性与节点对比

作者:流萤

时间:2026-10-24

浏览:513

本文介绍JavaScript中removeAttribute()方法用于删除指定元素属性的用法,包括参数说明及动态操作表格边框、自定义删除类名的示例。同时对比removeAttributeNode方法,解析两者在接收参数类型(属性名vs属性节点)及兼容性上的差异。

文章目录

在 JavaScript 中,可以通过元素的 removeAttribute() 方法来移除指定的属性。该方法的调用语法如下: removeAttribute(name)

参数 name 用于指定需要被删除的属性名称。

示例1

以下示例展示了如何动态控制表格边框的显示与隐藏。


<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() 方法重新设置边框的粗细值。

示例2

以下示例演示了如何封装一个自定义函数来删除指定的类名,并调用该函数执行操作。


<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 与 removeAttributeNode 方法异同

removeAttribute

该方法用于移除节点中指定名称的属性。具体示例如下


document.getElementById('riskTypePie').removeAttribute("style");

removeAttributeNode 注意:此方法在 IE 浏览器中不兼容。

使用步骤如下:

  • 首先获取需要删除属性的目标元素
  • 接着获取该元素上待删除的具体属性节点
  • 调用语法:<元素>.removeAttributeNode(<属性节点>)

var node=document.getElementById('chartWrap');
var attr=n.getAttributeNode('style');
node.removeAttributeNode(attr);

异同分析

相同点

  • 两种方法均用于移除节点的属性
  • 两种方法的调用对象必须为元素节点(标签节点)

不同点

  • removeAttribute 方法接收的参数为待删除属性的名称字符串
  • removeAttributeNode 方法接收的参数为待删除的属性节点对象本身

至此,关于 JavaScript 中 removeAttribute() 方法删除元素属性的介绍已完成。如需了解更多相关内容,可搜索本站过往文章或继续阅读后续文章,感谢支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章