html - How can I get h1 innerText in JavaScript without the innerText of its child? - Stack Overflow

admin2025-04-19  1

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?

Share edited Aug 28, 2020 at 22:50 HoldOffHunger 21k11 gold badges120 silver badges146 bronze badges asked Jan 3, 2020 at 7:10 Alireza_Ez73Alireza_Ez73 1392 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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>

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745072150a283347.html

最新回复(0)