![](/img/trans.png)
[英]JavaScript - Get contained text in DOM element in Javascript?
[英]How to get only directly contained text in DOM element in Javascript?
我有一個 div 里面有一些孩子,它直接包含如下文本:
<div id="price">
100$
<span>some ads</span>
<span>another ads</span>
for each
</div>
我想在這個 DOM 元素中直接包含文本“100$”。
我嘗試使用innerHTML
、 innerText
和textContent
。 但它們顯示所有文本,包括兒童文本,如下所示:
const element = document.getElementById('price'); console.log(element.innerText); console.log(element.innerHTML); console.log(element.textContent);
<div id="price"> 100$ <span>some ads</span> <span>another ads</span> for each </div>
預期結果是100$
(我不需要“for each”),它直接包含在父元素中的文本。 所以我可以得到價格和它的貨幣。
注:jquery也允許使用。
.clone()
克隆選定的元素。
.children()
從克隆元素中選擇子元素
.remove()
刪除先前選擇的子項
.end()
再次選擇被選元素
.text()
從沒有子元素的元素中獲取文本
const elementText = $("#price").clone().children().remove().end().text(); console.log(elementText.trim().split("\n")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent"> Parent <span>Child 1</span> <span>Child 2</span> </div> <div id="price"> 100$ <span>some ads</span> <span>another ads</span> for each </div>
編輯:你也可以使用這個:
$("#price").contents().get(0).nodeValue.trim()
過濾childNodes
以僅包含文本節點並使用每個匹配節點的textContent
:
const text = Array.prototype.filter
.call(element.childNodes, (child) => child.nodeType === Node.TEXT_NODE)
.map((child) => child.textContent)
.join('');
text
包括文本的完整標記,包括換行符。 如果這是不希望的,請使用text.trim()
。
使用filter.call
是因為childNodes
是一個NodeList
,它類似於數組,但不支持.filter
方法。
僅獲取第一個節點的文本
const text = Array.prototype.filter
.call(element.childNodes, (child) => child.nodeType === Node.TEXT_NODE)[0];
或者,如果您可以依賴該值始終是第一個孩子這一事實,則上述內容可以簡化為
const text = element.childNodes[0];
使用 jQuery:
const text = $($('#price').contents()[0]).text().trim();
您可以使用“outerText”屬性執行此操作。 如下例所示:
var text = document.querySelector('body').outerText; var regex = /([\d]+)\$/g; console.log(text.match(regex).join());
<div id="price"> 100$ <span>some ads</span> <span>another ads</span> for each </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.