HOWTO · jQuery

jQuery remove() 方法

本教程演示如何在 jQuery 中刪除元素。

remove() 方法從 jQuery 中的 DOM 中刪除元素。類似地,empty() 方法僅刪除 DOM 中選定元素的子元素。

本教程演示瞭如何在 jQuery 中使用 removeempty 方法。

jQuery remove() 方法

remove() 方法可以從 DOM 中刪除選定的元素。該方法將刪除選定的元素和元素內的所有內容。

此方法的語法如下。

$(selector).remove(selector)

其中 selector 是一個可選引數,指定是否刪除一個或多個元素,如果要刪除的元素不止一個,我們可以用逗號分隔它們。讓我們嘗試一個 remove() 方法的示例。

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#RemoveDiv").remove();
            });
        });
    </script>
</head>
<body>

    <div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">

        <h1> This Div Will be Removed </h1>
        <p>Paragraph one in the Div.</p>
        <p>Paragraph two in the Div.</p>

    </div>
    <br>
    <div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">

        <h1> This Div Will not be Removed </h1>
        <p>Paragraph one in the Div.</p>
        <p>Paragraph two in the Div.</p>

    </div>
    <button>Remove Div</button>

</body>
</html>

上面的程式碼將刪除選定的 div 及其子元素。見輸出:

jQuery remove 方法

正如我們所見,remove() 方法刪除了選定元素內的所有元素。另一種方法 empty() 僅刪除子元素。

jQuery empty() 方法

empty() 方法可以從選定元素中刪除所有子元素。它還會刪除子元素內的內容。

empty() 方法的語法如下。

$('selector').empty();

selector 可以是 id、類或元素名稱,讓我們嘗試 empty 方法的示例。

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $("#RemoveDiv").empty();
            });
        });
    </script>
</head>
<body>

    <div id="RemoveDiv" style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">
        Hello this is the div content
        <h1> This Div Content Will be Removed </h1>
        <p>Paragraph one in the Div.</p>
        <p>Paragraph two in the Div.</p>

    </div>
    <br>
    <div style="height:200px; width:300px; border:1px solid black; background-color:lightblue;">

        <h1> This Div Content Will not be Removed </h1>
        <p>Paragraph one in the Div.</p>
        <p>Paragraph two in the Div.</p>

    </div>
    <button>Remove Div</button>

</body>
</html>

上面的程式碼將只刪除 div 的子內容,而不是 div 本身。見輸出:

jQuery empty 方法