本文示範如何使用 jQuery 的 empty() 方法,刪除某元素本身以外的所有子元素與內容。
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").empty();
});
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>Empty the div element</button>
</body>
</html>
與 remove() 不同的是,empty() 只清空容器內部的內容與子元素,元素本身(含其 id、class、樣式)仍保留在頁面上。希望本文對大家的 jQuery 開發有所幫助。