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

Asked

Viewed 54 times

3

For example, in the structure below I have a div that has a text and another div which also has a text. How can I capture or verify if a text is the direct son of a tag, and not the son of another daughter 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>

1 answer

2


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

In this case types 1 and 3 is what you seek to distinguish:

Node.ELEMENT_NODE 1 An element like <p> or <div>.
Node.TEXT_NODE 3 The text of an element or attribute.

Thus, to capture only the text and not the content 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.