使用 JavaScript 刪除網頁中元素標籤之外的文字?
要刪除文字,請使用 remove() 的概念。使用 filter 來獲取元素標籤之外的內容。
假設我們的 HTML 如下 −
<div><h1>Demo Program</h1></div> This is also Demo Program
由於它不在元素標籤下,因此需要刪除“This is also Demo Program”。為此,可以使用 filter() 和 remove() 的完整程式碼如下 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div><h1>Demo Program</h1></div>
This is also Demo Program
<script>
$('body').contents().filter(function(){
return this.nodeType != 1;
}).remove();
</script>
</body>
</html>要執行上述程式,請儲存檔名“anyName.html(index.html)”並右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用 Live Server 開啟”選項。
輸出
這將產生以下輸出 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP