I want to get the innerText of <h1> without the innerText inside the span… this is the HTML of page:

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>

but this will return the innerText of both <h1> and <span>.

what can I do?

Answer

Once you select the parent, you’ll have to select its child text node, and get the contents of that node:

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>

Unfortunately there’s no way to navigate directly to a text node with a query string, so you have to go through the childNodes first.

Write a comment

Your email address will not be published. Required fields are marked *