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>
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?
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.
Try this.
var mainElement = document.getElementById("id_of_h1"),
innerElements = mainElement.firstChild,
innerTexts = [];
while (innerElements) {
if (innerElements.nodeType == 3) {
innerTexts.push(innerElements.data);
}
innerElements = innerElements.nextSibling;
}
var finalResult = innerTexts.join("");
finaresult will contain the intertext of the top element only.
In case you have <h1>hello <span>another</span> world
and need to get all text except html elements- hello world
not hello another world
,then you need to this way
const h1 = document.querySelector('div.col-md-8.info-header h1');
const el = h1.childNodes;
let result = "";
for(i=0;i<el.length;i++){
if(el[i].nodeName == '#text'){
result+=el[i].textContent;
}
}
console.log(result);
<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> extra text without tag
</h1>
</div>
</div>