HTML - DOM 元素 removeAttributeNode() 方法



removeAttributeNode() 方法允許您從元素中刪除特定的屬性節點。

語法

element.removeAttributeNode(attributeNode)

引數

此方法接受如下所述的單個引數。

引數 描述
attributeNode 您要從元素中刪除的節點物件。

返回值

removeAttributeNode() 方法返回從元素中刪除的屬性節點。

HTML DOM 元素“removeAttributeNode()”方法示例

以下是在 HTML DOM 元素中不同場景下使用 removeAttributeNode() 方法的一些示例。

刪除自定義資料屬性節點

此示例演示瞭如何使用 removeAttributeNode() 方法從<div> 元素中刪除自定義資料屬性節點。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Remove Custom Data Attribute Node</title>
</head>

<body>
    <h1>HTML DOM Element</h1>
    <h2>removeAttributeNode() Method</h2>
    <p>Click the button below to remove a custom data
        attribute node from the <div> element.
    </p>

    <div id="my" data-info="custom">
        This div has a custom data attribute.
    </div><br>

    <button onclick="removeDataAttributeNode()">
        Remove data-info Attribute
    </button>

    <script>
        function removeDataAttributeNode() {
            const div = document.getElementById('my');
            const attr=div.getAttributeNode('data-info');
            
            if (attr) {
                div.removeAttributeNode(attr);
                document.getElementById('o').textContent= 
                'Data attribute removed successfully.';
            } else {
                document.getElementById('o').textContent= 
                'Data attribute not found.';
            }
        }
    </script>
    <div id="o"></div>
</body>

</html>    

刪除 Href 屬性節點

此示例演示瞭如何使用 removeAttributeNode() 方法從元素中刪除 href 屬性節點。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Remove Attribute Node</title>
</head>

<body>
    <h1>HTML DOM Element</h1>
    <h2>removeAttributeNode() Method</h2>
    <p>Click the button below to remove the href 
        attribute from the anchor (<a>) element.
    </p>

    <a href="https://tutorialspoint.tw" id="my">
        Visit tutorialspoint.com
    </a><br><br>

    <button onclick="removeHrefAttribute()">
        Remove href Attribute
    </button>

    <div id="otpt"></div>

    <script>
        function removeHrefAttribute() {
            const link = document.getElementById('my');
            const hrefAttr=link.getAttributeNode('href');
            
            link.removeAttributeNode(hrefAttr);
            document.getElementById('otpt').textContent= 
            'Href attribute removed successfully.';    
        }
    </script>
</body>

</html>    

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
removeAttributeNode()
html_dom_element_reference.htm
廣告