如何在 JavaScript 中獲取 H1 元素的 innerText,而不包含其子元素的 innerText?
獲取 HTML 元素的文字內容是 Web 應用開發中的一項常見任務。在 JavaScript 中,可以使用 HTMLElement 物件的 innerText 屬性來實現。但是,這隻會返回特定元素內的文字,而不會返回其任何子元素的文字。
如果您只需要獲取 H1 標籤的 innerText,而不包含其子元素的 innerText,那麼有幾種方法可以實現。本文將討論一些在 JavaScript 中獲取 H1 標籤的 innerText(不包含其子元素的 innerText)的方法。
節點及其後代的渲染文字內容由 HTMLElement 介面的 innerText 屬性表示。作為一個 getter,它模擬了使用者使用游標突出顯示元素內容然後將其複製到剪貼簿時獲得的文字。
語法
以下是 JavaScript 中 innerText 的語法。
element.innerText
讓我們來看下面的例子,更深入地瞭解如何在 JavaScript 中獲取 h1 元素的 innerText,而不包含其子元素的 innerText。
示例
在下面的例子中,我們執行指令碼以獲取 JavaScript 中的 innerText。
<!DOCTYPE html> <html> <body> <div class="Bike"> <div class="Car"> <label for="name"><b>Actual Text:</b></label> <h1> This is BMW<span> That Was Ducati </span></h1> </div> </div> <h3>Innertext:</h3> <script> const h1 = document.querySelector('div.Car h1'); const text = h1.childNodes[0].textContent; document.write(text); </script> </body> </html>
示例
考慮下面的例子,我們執行指令碼以獲取 h1 元素的 innerText 並新增一些額外的訊息。
<!DOCTYPE html> <html> <body> <div class="tutorial"> <div class="tutorial1"> <label for="actual"><b>Actual Text:</b></label><br> <h1>Welcome <span>to the Tutorialpoint</span> HELLO </h1> </div> </div> <h1>Innertext:</h1> <script> const h1 = document.querySelector('div.tutorial h1'); const el = h1.childNodes; let result = ""; for(i=0;i<el.length;i++){ if(el[i].nodeName == '#text'){ result+=el[i].textContent; } } document.write(result); </script> </body> </html>
示例
讓我們來看另一個在 JavaScript 中獲取 innerText 的例子。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <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> <body> <div class="first-header"> <div class="second-header"> <h1> This is h1 tag........<span>This is span tag inside h1 tag.......... </span></h1> </div> </div> </body> <script> var valueOfh1 = document.querySelector('div.second-header h1'); var value = valueOfh1.childNodes[0].textContent; document.write(value); </script> </html>
廣告