HTML - DOM 元素 remove() 方法



remove() 方法允許您完全從網頁中刪除一個元素。

語法

element.remove();

引數

此方法不接受任何引數。

返回值

remove() 方法不返回任何值。

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

以下是 remove() 方法在 HTML DOM 元素中不同場景下的示例。

單擊刪除列表項

此示例演示瞭如何使用 remove() 方法透過單擊刪除按鈕逐一刪除列表 (<li>)。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Removing a List Item</title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>remove() Method</h2>
    <p>Click button and remove the list items!!</p> 
    <ul>
        <li>Apple 1
            <button onclick="remove(this)">Remove</button>
        </li>
        <li>Apple 2 
            <button onclick="remove(this)">Remove</button>
        </li>
        <li>Apple 3
            <button onclick="remove(this)">Remove</button>
        </li>
    </ul>

    <script>
        function remove(button) {
            button.parentNode.remove();
        }
    </script>
</body>

</html>    

刪除段落元素

此示例演示瞭如何使用 remove() 方法透過單擊刪除按鈕從網頁中刪除段落 (<p>) 元素。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Removing a Paragraph Element</title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>remove() Method</h2>
    <p>Click the button to remove a paragraph!!</p> 
    <p id="p">This is a paragraph.</p>

    <button onclick="removeParagraph()">
        Remove Paragraph
    </button>

    <script>
        function removeParagraph() {
            const paragraph=document.getElementById('p');
            paragraph.remove();
        }
    </script>
</body>

</html>    

支援的瀏覽器

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