0

var el = document.getElementById("parentDiv");
console.log(el.textContent);
console.log(el.innerText);
console.log(el.innerHTML);
<div id="parentDiv">
  parent div
  <p>p</p>
  <div>
    this text is in a div

    <span>span</span>
    <a>im a link!</a>
    <div>
      another div
      <div>
        <span><a>link in a span</a></span>
      </div>
    </div>
  </div>
</div>

When running this, it always returns 'parent div' plus all the text from the child elements. Is there a way to only return 'parent div' using js?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Ra'ed Alaraj
  • 173
  • 1
  • 15

2 Answers2

5

Loop over all the child nodes, skip any which are not text nodes, take the text from those.

var el = document.getElementById("parentDiv");
var text = "";
for (let i = 0; i < el.childNodes.length; i++) {
    let node = el.childNodes[i];
    if (node.nodeType  === Node.TEXT_NODE) {
        text += node.data;
    }
}
console.log(text);
<div id="parentDiv">
  parent div
  <p>p</p>
  <div>
    this text is in a div

    <span>span</span>
    <a>im a link!</a>
    <div>
      another div
      <div>
        <span><a>link in a span</a></span>
      </div>
    </div>
  </div>
</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

One of the easiest ways is to clone the parent, remove the non-TEXT-NODE children from the clone, and then get the text:

const element = document.getElementById('parent');
const clone = element.cloneNode(true); // use deep

Array.prototype.slice.call(clone.children).forEach(child => {
  child.nodeType !== Node.TEXT_NODE && clone.removeChild(child);
});

const result = clone.innerHTML;

console.log(result);
<div id="parent">
 PARENT
 <div>A</div>
 <div>B</div>
 <div>C</div>
</div>
samanime
  • 25,408
  • 15
  • 90
  • 139