jQuery empty() 方法



jQuery 中的 empty() 方法用於移除選定元素的所有子節點和內容。換句話說,它會刪除選定元素中的所有文字、HTML 和子元素,使其為空。

此方法對元素是 “非破壞性” 的,因為它不會移除選定的元素本身或其屬性,只會移除其內容。

語法

以下是 jQuery 中 empty() 方法的語法:

$(selector).empty()

引數

此方法不接受任何引數。

示例 1

在以下示例中,我們使用 empty() 方法移除 "div" 元素的所有子節點和內容:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("div").empty();
            });
        });
    </script>
</head>
<body>
    <div style="border: 2px solid black; width: 20%;">
        <p style="background-color: yellow;">This is some text inside the container.</p>
        <p style="background-color: yellow;">This is another paragraph.</p>
    </div>
    <button>Clear Content</button>
</body>
</html>

當我們點選按鈕時,"div" 元素內部的所有 "paragraph" 元素將被移除。

示例 2

在此示例中,我們移除 "ul" 元素的所有子節點和內容:

<html>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("#myList").empty();
            });
        });
    </script>
</head>
<body>
    <ul id="myList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <button>Empty List</button>
</body>
</html>

點選按鈕後,"ul" 元素內部的所有 "list" 元素將被移除。

jquery_ref_html.htm
廣告

© . All rights reserved.