Question:
For example, in the structure below I have a div
that has text and another div
that also has text. How can I capture or verify that a text is a direct child of a tag, and 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>
Answer:
Although not visually visible this text and the child element are nodes ( nodes
) different. And you can check that with .nodeType
.
In this case, types 1 and 3 are what you are trying to distinguish:
Node.ELEMENT_NODE
1
An element such as<p>
or<div>
.
Node.TEXT_NODE3
The text of an element or attribute.
So, 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>