[英]Accessing child element through parent class in JavaScript
如何通過JavaScript中的類通過父元素訪問子元素的innerHTML
,它沒有類或ID?
它應該只返回<b>
標簽之間的text
。
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
嘗試使用querySelector()和textContent
:
var txt = document.querySelector('.parent.element > h5 > b').textContent; console.log(txt)
<div class="parent element"> <h5> some other text<b>text</b> </h5> </div>
您可以將document.querySelector()
與CSS選擇器(如.parent.element h5 b
document.querySelector()
一起使用,它將在h5
標記內找到包含parent
和element
類的元素內的b
標記。
然后你可以使用textContent
來獲取文本,或者使用innerHTML
來獲取文本和標記。
console.log(document.querySelector('.parent.element h5 b').textContent); // sample when using innerHTML grabbing the h5 console.log(document.querySelector('.parent.element h5').innerHTML); // sample when using textContent grabbing the h5 console.log(document.querySelector('.parent.element h5').textContent);
<div class="parent element"> <h5> some other text<b>text</b> </h5> </div>
關於textContent
vs innerText
注釋:
Internet Explorer引入了
node.innerText
。 意圖類似於node.textContent
但有以下區別:
雖然
textContent
獲取所有元素的內容,包括<script>
和<style>
元素,但innerText
卻沒有。
innerText
知道樣式,不會返回隱藏元素的文本,而textContent
會。由於
innerText
知道CSS樣式,它將觸發重排,而textContent
不會。與
textContent
不同,在Internet Explorer中更改innerText
(包括版本11)不僅會從元素中刪除子節點,還會永久地銷毀所有后代文本節點(因此無法將節點再次插入任何其他元素或相同的元素中元素)。
var innerText=document.querySelector('.parent.element h5 b').innerText console.log(innerText);
<div class="parent element"> <h5> some other text<b>text</b> </h5> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.