通过 JavaScript 中的父类访问子元素



如何在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标签,在具有类parentelement的元素内。

然后,您可以使用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>

关于

textContentinnerText的注意事项:

IE浏览器node.innerText推出 .意图类似于node.textContent但有以下区别:

  • 虽然textContent获取所有元素的内容,包括<script><style>元素,但innerText不会。

  • innerText知道样式,不会返回隐藏元素的文本,而textContent会。

  • 正如innerText知道CSS样式一样,它会触发重排,而textContent不会。

  • textContent不同,在Internet Explorer(包括版本11)中更改innerText不仅会从元素中删除子节点, 但也永久破坏所有后代文本节点(所以它是 无法再次将节点插入任何其他元素或 不再是相同的元素)。

最新更新