我想获取 <h1>
的 innerText没有 innerText
在跨度内...这是页面的 HTML:
var title = document.querySelector('div.col-md-8.info-header h1');
title = title && title.innerText;
console.log(title);
<div class="col-md-12 header">
<div class="col-md-8 info-header">
<h1> This note is for h1 tag!!!!!! <span> this note is insidespan v226hql!!! </span>
</h1>
</div>
</div>
但这将返回 innerText
两者的<h1>
和 <span>
.
我能做什么?
最佳答案
一旦选择了父节点,就必须选择其子节点文本节点,并获取该节点的内容:
const h1 = document.querySelector('div.col-md-8.info-header h1');
const text = h1.childNodes[0].textContent;
console.log(text);
<div class="col-md-12 header">
<div class="col-md-8 info-header">
<h1> This note is for h1 tag!!!!!! <span> this note is insidespan v226hql!!! </span>
</h1>
</div>
</div>
不幸的是,无法直接导航到带有查询字符串的文本节点,因此您必须先通过childNodes
。
关于javascript - 如何在没有其子项的 innerText 的情况下在 JavaScript 中获取 h1 innerText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574530/