Check if text belongs to the element and not to the child

3

For example, in the structure below I have a div that has a text and another div that also has text. How can I capture or check if a text is a child direct from a tag, not a child of another child tag:

console.log(document.querySelector('.div1').textContent)
.div1{
  background: #ccc;  
  padding: 10px
}
.div2{
  background: #999;  
  padding: 10px
}
<div class="div1">
  Texto filho direto da div1
  <div class="div2">
    Texto filho direto da div2 e filho indireto da div1
  </div>
</div>
    
asked by anonymous 21.08.2016 / 02:14

1 answer

2

Although visually not visible, this text and the child element are different nodes ( nodes ). And you can check this out with .nodeType .

In this case, types 1 and 3 are what you are trying to distinguish:

  

Node.ELT_NODE 1 An element or a text of an element or attribute .

So, to capture only the text and not the contents of the offspring:

var pai = document.querySelector('.div1');
var text = '';
for (var i = 0; i < pai.childNodes.length; ++i) {
  var el = pai.childNodes[i];
  if (el.nodeType === 3) text += el.textContent;
}

console.log(text);
<div class="div1">
  Texto filho direto da div1
  <div class="div2">
    Texto filho direto da div2 e filho indireto da div1
  </div>
</div>
    
21.08.2016 / 07:29