如何在JavaScript中通过带有class的父元素访问没有类或ID的子元素innerHTML
?
它应该只返回<b>
标记之间的text
。
<div class="parent element">
<h5>
some other text<b>text</b>
</h5>
</div>
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>
尝试使用 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
,它将在h5
标签内找到一个b
标签,在具有类parent
和element
的元素内。
然后,您可以使用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
与innerText
的注意事项:
IE浏览器
node.innerText
推出 .意图类似于node.textContent
但有以下区别:
虽然
textContent
获取所有元素的内容,包括<script>
和<style>
元素,但innerText
不会。
innerText
知道样式,不会返回隐藏元素的文本,而textContent
会。正如
innerText
知道CSS样式一样,它会触发重排,而textContent
不会。与
textContent
不同,在Internet Explorer(包括版本11)中更改innerText
不仅会从元素中删除子节点, 但也永久破坏所有后代文本节点(所以它是 无法再次将节点插入任何其他元素或 不再是相同的元素)。