1. 程式人生 > 程式設計 >JS removeAttribute()方法實現刪除元素的某個屬性

JS removeAttribute()方法實現刪除元素的某個屬性

在 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方法接收的是要刪除的屬性節點它本身

到此這篇關於JS removeAttribute()方法實現刪除元素的某個屬性的文章就介紹到這了,更多相關JS removeAttribute()刪除元素屬性內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!