How do I check an element's direct textContent?

Viewed 1072

Say I have an element structure like so

<div>
   This is direct text

   <div>
       This is text nested in a child element
   </div>
</div>

Is there a way to check the direct text content of the parent div without checking the content of the inner children?

Consequentially if I had a structure like this

<div id="uppermost-div">
  <div>
     This is direct text

     <div>
       This is text nested in a child element
     </div>
   </div>
</div>

And I checked this direct text content of the #uppermost-div I would expect to be null or empty string or something.

Is there a way to accomplish checking values like that in HTML/Javascript?

2 Answers

See comments.

// Make a deep copy of the parent
let tempElement = document.getElementById("uppermost-div").cloneNode(true);

// Loop over the elements within the copy
tempElement.querySelectorAll("*").forEach(function(el){
  el.remove(); // remove the children
});

// Log the text of what's left
console.log(tempElement.textContent);
<div id="uppermost-div">
  <div>
     This is direct text

     <div>
       This is text nested in a child element
     </div>
   </div>
</div>

Related